Skip to content

About updating state in React #149008

Answered by ZoroXCode
KIMLENDING asked this question in General
Discussion options

You must be logged in to vote

Question:

Why does the value of count1 quadruple instead of doubling? Why is setCount1 executed twice in a row?


Answer:

The behavior occurs because of nested functional updates and the way React batches state updates for performance optimization. In your useEffect hook, setCount1 is called inside the functional update of setCount. This causes setCount1 to be executed twice during the same render cycle:

  1. React schedules the first update for setCount1(pr => pr * 2), which doubles the value of count1.
  2. After the first state update, React re-runs the state logic again due to the nested functional updates, causing setCount1 to execute a second time. This doubles the value of count1 again, resu…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by KIMLENDING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
2 participants