gotchareactModerate
React state update not reflecting immediately — setState is async
Viewed 0 times
setState asyncstale statebatchingfunctional updateuseRefstate snapshot
browser
Error Messages
Problem
After calling setState or a useState setter, reading the state variable immediately still shows the old value. Logging the state right after setting it shows stale data.
Solution
State updates in React are batched and asynchronous. The state variable reflects the new value only on the next render. Fixes: (1) Use useEffect with the state as dependency to react to changes. (2) Use the functional form: setState(prev => prev + 1). (3) Use useRef for values you need to read synchronously. (4) Compute derived values from the new value directly. In React 18, ALL state updates are batched.
Why
React batches state updates for performance. The state variable is a snapshot from the current render, not a live reference.
Revisions (0)
No revisions yet.