Why can a state update seem to use an old value, and how do you fix it?
Model answer
State inside a render is a snapshot. If you call setCount(count + 1) three times in one handler, all three use the same old count, so the result is only +1. Use the updater form, setCount((c) => c + 1), which receives the latest value each time.
The same snapshot idea applies to closures in timers and effects: they can capture old state unless you use updater functions, refs or correct dependencies.
Learn this topic
React useState Explained: Make Your Page React to Change in the course React.js Full Course: Beginner to Advanced.
Sign in to add your own answer.