Why setState(prev => ...) Exists
What you'll learn: Why React offers a function form of setState when you need to compute the next state based on the current state.
The Closure Capture Problem
Remember that state updates are asynchronous and you can't rely on state mid-render. When you call setState(newValue) multiple times quickly, or when you need the latest state to calculate the next state, you might not be working with the value you expect.
Here's the issue: if you do setCount(count + 1) twice in one event handler, both calls "see" the same count value from that render. It's like taking two photos at the same moment — both photos show the same scene, even if you expected the second to show changes from the first.
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1); // Reads count = 0
setCount(count + 1); // Still reads count = 0
// Result: count becomes 1, not 2!
}
return <button onClick={handleClick}>{count}</button>;
}
Both setCount calls captured count = 0 from the current render. They don't "see" each other's updates.
The Solution: Updater Function
Pass a function to setState instead:
function handleClick() {
setCount(prev => prev + 1); // Uses latest value
setCount(prev => prev + 1); // Uses result of previous update
// Result: count becomes 2 ✓
}
React guarantees the prev parameter is always the most recent state value, even if multiple updates are queued.
Key Takeaway: Use setState(prev => ...) whenever your next state depends on the current state — it ensures you're computing from the latest value, not a stale snapshot from the render where setState was called.