Why should I use a functional state update?
Try code in the playgroundUnderstand the concept
A functional state update supplies a function that receives the pending previous state and returns the next state. It is useful when several updates may be queued or a callback holds an older render's value. React can apply these updater functions in order without each relying on the same captured value.
Important ideas
-
Use
setCount(c => c + 1)when the next value depends on the previous value. -
It avoids reading an old value from a closure during queued updates.
-
setCount(count + 1)twice in one handler usually adds only one. -
Updater functions should be pure; do not send requests or mutate external data inside them.
Example — inside an event handler:
setCount(count + 1);
setCount(count + 1); // Both use the same render's count: usually +1 total.
// Alternative:
setCount(c => c + 1);
setCount(c => c + 1); // Each uses the pending previous value: +2 total.- These are two alternative approaches, not four calls intended to be used together.
Can you explain it without the notes?
Why should I use a functional state update?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
A functional state update supplies a function that receives the pending previous state and returns the next state. It is useful when several updates may be queued or a callback holds an older render's value. React can apply these updater functions in order without each relying on the same captured value.
Turn this concept into a clear answer.
- State is a snapshot for a render, so reading it immediately after calling a setter does not give the next render's value.
Adapted from 06_REACT_NEXTJS.md · “Why should I use a functional state update?”. Examples are study fragments; framework behavior can depend on your version.