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

The Functional Update Solution

Using the updater function pattern to always access current state in async contexts without capturing values.

The Functional Update Solution

What you'll learn: How to fix stale state in asynchronous callbacks by using the updater function pattern.

The Problem Recap

You've seen how setTimeout, setInterval, and other async callbacks can capture old state values — the infamous stale closure problem. When your callback finally runs, it's using the state value from when it was created, not the current state.

The Functional Update Fix

Here's the beautiful solution: use the functional update form of your state setter inside async callbacks:

const [count, setCount] = useState(0);

function startTimer() {
  setTimeout(() => {
    // ❌ BAD: captures stale count
    setCount(count + 1);

    // ✅ GOOD: always gets current state
    setCount(prev => prev + 1);
  }, 3000);
}

The functional update prev => prev + 1 doesn't read from the captured count variable. Instead, React guarantees that prev is the actual current state when the update runs, no matter how much time has passed or how many other updates happened.

Why This Works

Think of it like giving React instructions instead of a final value. You're saying "take whatever the current count is and add 1" rather than "set it to this specific number I calculated 3 seconds ago."

This pattern works anywhere state might be stale: setTimeout, setInterval, event listeners added once, WebSocket callbacks, or any closure that outlives its render.

Key Takeaway: When updating state in async callbacks or closures that might capture stale values, always use the functional update form setState(prev => ...) to guarantee you're working with current state.