Using Functional Updates to Avoid Staleness
You'll learn why setCount(c => c + 1) is the bulletproof way to update state in async contexts.
When you use an async callback (like setTimeout or a .then() chain), your closure captures a snapshot of state from when the function was created. This creates the "stale state" problem—you're working with old values.
The functional update pattern solves this elegantly: the updater function runs at commit time, not when you call it. React guarantees that the parameter passed to your updater (like c in c => c + 1) will be the latest state value at the moment React commits the update.
Why This Works
Think of it like leaving instructions instead of a fixed value:
- Direct update: "Set count to 5" (what if count changed since you decided on 5?)
- Functional update: "Whatever count is when you apply this, add 1 to it"
When React processes your update during the commit phase, it evaluates your function with the most current state. Even if multiple updates are batched or time has passed since your callback ran, your logic stays correct.
// In an async context:
setTimeout(() => {
setCount(count + 1); // ❌ Uses stale 'count' from closure
setCount(c => c + 1); // ✅ Uses latest state at commit time
}, 1000);
This is especially critical when multiple async operations might fire out of order, or when updates are batched together.
Key Takeaway: Functional updates setState(prev => newValue) guarantee your logic runs with the latest state at commit time, eliminating staleness in async callbacks.