Answer the question
In order to leave comments, you need to log in
Why does useState work like this?
Good day.
There is a component:
import { useEffect, useState } from 'react';
import { getRandomIntInRange } from './utills';
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const Test = () => {
const [test] = useState(() => getRandomIntInRange(0, arr.length - 1));
const [inputValue, setInputValue] = useState('');
console.log('component', test); // после перерендера новое значение
useEffect(() => {
console.log('useEffect', test); // все ок, вызывается один раз, значение не меняется
}, [test]);
const handleInputChange = (e) => setInputValue(e.target.value);
return <input type="text" onChange={handleInputChange} value={inputValue} />;
};
const getRandomIntInRange = (min = 0, max = 0) => {
const minNumber = Math.ceil(min);
const maxNumber = Math.floor(max);
return Math.floor(Math.random() * (maxNumber - minNumber + 1) + minNumber);
};
component 5
...ввожу данные в инпут для перерендера компонента...
component 0
component 0
component 0
useEffect 3
...ввожу данные в инпут для перерендера компонента...
component 3
component 3
Answer the question
In order to leave comments, you need to log in
This works because of StrictMode in React, because in this mode, at the development stage, React makes an additional check and makes calls to some methods twice (in fact, this is visible in the console):
Strict mode is not able to automatically detect side effects, but it helps to track them by making them more deterministic. This behavior is achieved by calling the following methods twice:
- The constructor, render, and shouldComponentUpdate methods of a class component
- GetDerivedStateFromProps class bean static method
- The body of a functional component
- Update functions (first argument to setState)
- Functions passed to useState, useMemo, or useReducer
console.log("component", test);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question