Course contentsShow
← React
Lesson 441 of 2,39612. Rendering and BatchingFree lesson

Async Functions and Stale State

Why state read inside setTimeout or after await can be outdated—the closure captured an old render's value.

Async Functions and Stale State

What you'll learn: Why state values read inside async functions or after await can be outdated—the closure captured an old render's snapshot.

The Problem with Async and State

When you use async/await in React, your function pauses at each await and resumes later. But here's the catch: the state value you read after the await is still from the render when the function started, not from the current render.

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

  const handleClick = async () => {
    console.log('Before await:', count); // e.g., 0
    await fetch('/api/data');
    console.log('After await:', count); // Still 0, even if count changed!
    setCount(count + 1); // Uses stale value
  };

  return <button onClick={handleClick}>Count: {count}</button>;
}

If the user clicks multiple times rapidly, each async function captures its own count snapshot. All of them might use 0, leading to bugs.

Why This Happens

When the async function is created, it closes over the count variable from that specific render. While the function is paused (waiting for the API), React might re-render with a new count value, but your paused function doesn't see it—it still has the old value captured in its closure.

The Solution

Use the functional update form of setState:

await fetch('/api/data');
setCount(prev => prev + 1); // Always uses current state

Now you're guaranteed to work with the latest value, regardless of how many renders happened while you were waiting.

Key Takeaway: State values read inside async functions (especially after await) are snapshots from when the function started—use functional updates to avoid stale state bugs.