Course contentsShow
← React
Lesson 574 of 2,39616. useEffect for Data FetchingFree lesson

The Stale Closure Problem

Recognize how closures in async functions can capture old state values, leading to incorrect data updates.

The Stale Closure Problem

What You'll Learn: How async functions inside useEffect can capture outdated state values, causing bugs when updates arrive late.

The Core Problem

When you start a data fetch inside useEffect, that fetch is asynchronous — it takes time. The function you pass to .then() or use with await "closes over" (captures) the props and state values that existed when the effect ran. If your component re-renders while the fetch is still in flight, those captured values become stale — they no longer match the current state of your component.

When the fetch finally completes, the callback uses the old, captured values to update state, potentially overwriting newer data or setting state that's no longer relevant.

A Real-World Analogy

Imagine you order a pizza (start a fetch) and write down your current address on a sticky note. While the pizza is being made, you move to a new house (component re-renders with new state). The pizza still gets delivered to the old address on the sticky note — the delivery driver is using stale information.

The Symptom

// BAD: userId changes, but old fetch completes last
useEffect(() => {
  fetch(`/api/user/${userId}`)
    .then(res => res.json())
    .then(data => setUser(data)); // Uses captured userId
}, [userId]);

If userId changes from 1 to 2 quickly, you might fetch user 1, then fetch user 2, but user 1's response arrives last — so you display the wrong user!

Why It Matters

Stale closures cause race conditions: whichever fetch finishes last wins, regardless of which request was made most recently. This leads to displaying incorrect data.

Key Takeaway: Async callbacks in useEffect capture variables from when the effect ran, not when they complete — if state changes in between, you're working with stale data.