Course contentsShow
← React
Lesson 369 of 2,39611. useState Patterns and PitfallsFree lesson

The Closure Trap with Direct Updates

How setState(count + 1) in async code or callbacks can use an old value, causing missed updates or incorrect results.

The Closure Trap with Direct Updates

What you'll learn: Why using setState(count + 1) in async code or callbacks can silently use stale values and produce wrong results.


The Problem: Closures Capture Old Values

When you write setState(count + 1) inside a callback or async function, you're referencing the count variable from when that function was created. JavaScript closures "freeze" the value of count at that moment.

If multiple updates happen quickly, or if your callback runs after a delay, each one might read the same old value instead of the latest state.

Analogy: Imagine writing "add 1 to the current balance" on three sticky notes based on seeing 10inyouraccount.Youhandallthreenotestoabankteller.Theyprocessthemonebyone,buteachnotesays"10 in your account. You hand all three notes to a bank teller. They process them one by one, but each note says "10 + 1 = 11"becausethat′swhatyouwrote.Finalbalance:11" because that's what you wrote. Final balance: 11. You expected $13.


Where This Bites You

// ❌ TRAP: Both clicks may use count = 0
const [count, setCount] = useState(0);

function handleClick() {
  setTimeout(() => {
    setCount(count + 1); // "count" is 0 when timeout was created
  }, 1000);
}

Click twice fast → two timeouts capture count = 0 → both set state to 1, not 2.


Why It Matters

  • Async code (timers, fetch) often runs after other updates
  • Event handlers in loops or maps can all capture the same initial value
  • You lose updates silently—no errors, just wrong numbers

Key Takeaway: Direct updates like setState(value + 1) read from a closure snapshot that can be stale. If updates can overlap or happen asynchronously, you'll get incorrect results or lose updates entirely.