Passing a function to a state setter (setCount(c => c + 1), or this.setState(prev => …) in classes) tells React: "compute the next state from the latest pending state, not from the value this render captured." React queues updater functions and applies them in order during the next render. Use it whenever the next state depends on the previous state, especially with several updates in one event, inside async callbacks, timers and effects, or to keep a callback's dependencies stable.
function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1); // count is 0 in this render
setCount(count + 1); // still 0
setCount(count + 1); // still 0
}
// Result: 1, not 3
}
Every render has its own constant count. Setters don't mutate it. They schedule a re-render. With automatic batching (React 18+), all three calls are processed together, and each says "set to 1".
function addThree() {
setCount(c => c + 1); // queue: 0 → 1
setCount(c => c + 1); // 1 → 2
setCount(c => c + 1); // 2 → 3
}
During the next render React walks the queue: plain values replace the state, and functions receive the result of the previous step.
1. Async callbacks and stale closures
useEffect(() => {
const id = setInterval(() => {
setSeconds(s => s + 1); // always fresh, no dependency on `seconds`
}, 1000);
return () => clearInterval(id);
}, []); // safe with an empty dependency array
Writing setSeconds(seconds + 1) would freeze at 1, because the closure captured seconds = 0. Or you'd need seconds in the dependencies, which restarts the interval every second.
2. Stable callbacks
const toggle = useCallback(() => setOpen(o => !o), []);
No dependency on open, so the function identity never changes, which helps memoized children.
3. Reducer-like updates of objects and arrays
setTodos(prev => prev.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
This guarantees you transform the latest list even if another update was queued first.
prev.setName(e.target.value)).useReducer is the next step up.this.setState(updater, callback). The updater has the shape (prevState, props) => partialState. The optional second argument runs after the update is committed. The function-component equivalent is a useEffect reacting to the new state.
useCallback dependencies empty.Spotted a mistake or a rights concern? Report an issue