recently i came around this problem statement, where i needed to tell the value that will be printed on the button for the below react code.
export function App() {
const [count1, setCount1] = useState(1);
const [count2, setCount2] = useState(count1 + 1);
console.log('count1 :', count1);
console.log('count2 :', count2);
useEffect(() => {
setCount2((prev) => prev + count1);
}, [count1])
return (
<button onClick={() => {
setCount1(count2 + 1)
}}>
{count2 / count1}
</button>
);
}
my initial guess was that the value of count2 will be 2 and the value printed on the button will be 2/1 > 2. But on running it locally, i got to know that the answer was 4.
can someone explain to me why the value of count2 becomes 4?
2
Answers
The hook useEffect is called 2 times in React Strict mode. The initial value for count2 is 2 and when useEffect is called twice, you can see that count2 is 4.
Running in non-strict mode:
count1 = 1; count2 = 2
count1 = 1; count2 = 3
So, the label initially shown in the button will be
3
.If you now click on the button:
count1 = 4; count2 = 3
count1 = 4; count2 = 7
.The button will show
1.75
.Running in strict mode:
count1 = 1; count2 = 2
count1 = 1; count2 = 3
count1 = 1; count2 = 4
So, in this case the label of the button will be
4
.If you now click on the button:
count1 = 5; count2 = 4
count1 = 5; count2 = 9
count1 = 5; count2 = 14
.The button will show
2.8
.