InterviewBuddy
All interview questions

How do you avoid stale state in repeated updates?

Intermediate

Answer

When the next state depends on the previous state, pass an updater function. React processes updater functions against the queued state instead of the value captured by the current render.

Explanation

Calling setCount(count + 1) several times in one handler reuses the same captured count. An updater expresses the intended sequence.

Example

setCount(c => c + 1); setCount(c => c + 1);