Update state from the previous value
Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.
Calling setCount(count + 1) three times in one handler adds one, not three, because every call reads the same count from that render. An updater function reads the latest queued value instead.
import { useState } from 'react';
export function AddThree() {
const [direct, setDirect] = useState(0);
const [updater, setUpdater] = useState(0);
function handleClick() {
setDirect(direct + 1);
setDirect(direct + 1);
setDirect(direct + 1);
setUpdater((n) => n + 1);
setUpdater((n) => n + 1);
setUpdater((n) => n + 1);
}
return (
<button onClick={handleClick}>
direct {direct}, updater {updater}
</button>
);
}direct 0, updater 0 (before the click)
direct 1, updater 3 (after one click)React batches the updates of one event and renders once. Each setDirect(direct + 1) was computed from the same direct of 0, so they all queue the value 1. Each n => n + 1 receives the result of the one before it, which gives 3. This queue is described in Updating state based on the previous state.
Use the updater form whenever the new value is derived from the old one, especially in timers and async code, where the closure may be stale.