useState: Updates, Batching & Functional State
useState gives a component local state. Calling its setter schedules a state update; it does not synchronously mutate the variable from the current render.
When a new state depends on the previous state, use the functional updater form. This is especially important when multiple updates can be batched or when callbacks capture an older render.
State should represent information that can change and that affects rendering. Avoid storing values that can be computed cheaply from existing props or state.
Functional state update
const [count, setCount] = useState(0);
function incrementTwice() {
setCount(c => c + 1);
setCount(c => c + 1);
}💡 Each updater receives the latest queued value, so two increments produce a net increase of two.
Key Takeaways
- State setters schedule a new render; they do not mutate the current render's variable.
- Use functional updates when next state depends on previous state.
- Keep derived values out of state when possible.
Knowledge Check
Why use `setCount(c => c + 1)` instead of `setCount(count + 1)` when chaining updates?