Course contentsShow
← React
Lesson 883 of 2,39623. useMemo and useCallbackFree lesson

Stale Closures in Memoized Functions

Understanding how missing dependencies create callbacks that reference outdated values.

Stale Closures in Memoized Functions

You'll learn: How missing dependencies in useMemo and useCallback cause your functions to "remember" outdated values from previous renders.

The Problem: Trapped Values

When you create a memoized function with useCallback or useMemo, React "freezes" that function in memory. The function captures all the variables it references at that moment — this is called a closure. If you forget to list a variable in the dependency array, the memoized function keeps using the old value from when it was first created, even as your component re-renders with new values.

Think of it like taking a photograph of your workspace. If you refer to that photo later, you see your desk exactly as it was then — not how it looks now. The photo is "stale" if things have changed.

How It Happens

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

  // ❌ Missing 'count' in dependencies
  const logCount = useCallback(() => {
    console.log(count);
  }, []); // Empty array = function never updates

  // logCount will ALWAYS log 0, even when count is 5, 10, etc.
}

The logCount function captured count when it was 0. Because the dependency array is empty, React never recreates the function, so it never sees the updated count values.

The Fix

const logCount = useCallback(() => {
  console.log(count);
}, [count]); // ✅ Now the function updates when count changes

With count in the dependency array, React recreates logCount whenever count changes, giving it access to the current value.

Key Takeaway: A memoized function without all its dependencies in the array becomes a "stale closure" — frozen with outdated values, leading to bugs where your code appears to ignore state changes.