Functional Update Syntax
You'll learn how to guarantee your state updates use the freshest value every time.
The Pattern
When you call setState(prevState => newState), React gives you the most current state value as prevState, and you return the new state based on it. This is called functional update syntax.
const [count, setCount] = useState(0);
// Direct update (can be stale)
setCount(count + 1);
// Functional update (always fresh)
setCount(prevCount => prevCount + 1);
Why This Matters
Remember from the previous lesson that multiple setState calls or closures can trap old state values? The functional form solves this by asking React: "What's the latest value right now?" — not relying on what you captured when the function was created.
Think of it like checking your bank balance right before making a withdrawal, rather than using a balance you wrote down hours ago.
When to Use It
Use functional updates whenever your new state depends on the old state:
// Increment counter
setCount(prev => prev + 1);
// Toggle boolean
setIsOpen(prev => !prev);
// Update based on previous value
setScore(prev => prev + points);
If your new state doesn't depend on the old value, direct updates are fine:
// This is perfectly okay
setName('Alice');
setIsOpen(false);
The Mental Model
The function you pass runs later, at the moment React applies the update. By then, prevState reflects any earlier updates that were queued. You're working with reality, not memory.
Key Takeaway: Use setState(prev => ...) whenever the new state depends on the old state — it guarantees you're working with the latest value, not a stale closure.