EN
React - useState set method does not reflecting my change immediately
1 answers
5 points
Hi there!
What is the problem with my component? When I try to set state, and use it again the state doesn't reflect previous change. What is wrong with my code?
xxxxxxxxxx
1
const Calculator = ({a, b, operator}) => {
2
const [result, setResult] = useState();
3
useEffect(() => {
4
if (operator === '+') {
5
setResult(a + b)
6
}
7
console.log('Result: ' + result); // <------ logs wrong value
8
}, [a, b, operator]);
9
return (
10
<div>Result: {result}</div>
11
);
12
};
Why component dysplays proper result on my site, and console logs wrong result value?
1 answer
7 points
useState
setter schedules update action that will be visible in the next rendering cycle.
useState
set operation is `asynchronous` and will not be reflected immediately.
You can try to use the following source code to see the result change effect:
xxxxxxxxxx
1
const Calculator = ({a, b, operator}) => {
2
const [result, setResult] = useState();
3
useEffect(() => {
4
if (operator === '+') {
5
setResult(a + b)
6
}
7
}, [a, b, operator]);
8
useEffect(() => {
9
console.log('Result: ' + result); // <------ solution for wrong value in question code
10
}, [result]);
11
return (
12
<div>Result: {result}</div>
13
);
14
};
second useEffect()
will be triggered always on result
changed, and after the component will be mount/ready.
Alternative solutions
1. Helper newResult
variable/constant:
xxxxxxxxxx
1
const Calculator = ({a, b, operator}) => {
2
const [result, setResult] = useState();
3
useEffect(() => {
4
if (operator === '+') {
5
const newResult = a + b;
6
setResult(newResult);
7
console.log('Result: ' + result); // <------ solution for wrong value in question code
8
}
9
}, [a, b, operator]);
10
return (
11
<div>Result: {result}</div>
12
);
13
};
1. Setter with callback:
xxxxxxxxxx
1
const Calculator = ({a, b, operator}) => {
2
const [result, setResult] = useState();
3
useEffect(() => {
4
if (operator === '+') {
5
setResult(result => {
6
const newResult = a + b;
7
console.log('Result: ' + result); // <------ solution for wrong value in question code
8
return newResult;
9
});
10
}
11
}, [a, b, operator]);
12
return (
13
<div>Result: {result}</div>
14
);
15
};
0 commentsShow commentsAdd comment