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

Every Referenced Value Must Be in the Array

Why all props, state, and variables used inside useMemo/useCallback must appear in dependencies.

Every Referenced Value Must Be in the Array

What you'll learn: Why every prop, state variable, or local value you use inside useMemo or useCallback must appear in the dependency array.

The Core Rule

When you use useMemo or useCallback, React needs to know when to recalculate or recreate the memoized value. The dependency array tells React which values to "watch" for changes. If you use a value inside the callback but don't list it in the array, React won't know to update when that value changes.

This leads to stale closures—your memoized function or value keeps using old data even though the actual variable has changed.

Why This Matters

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

// ❌ WRONG: multiplier is missing from dependencies
const result = useMemo(() => {
  return count * multiplier;
}, [count]);

In this broken example, when multiplier changes, result won't recalculate. It will keep using the old value of multiplier because React doesn't know to invalidate the cache.

// ✅ CORRECT: all referenced values included
const result = useMemo(() => {
  return count * multiplier;
}, [count, multiplier]);

The Analogy

Think of the dependency array as a checklist for a recipe. If your recipe uses flour, eggs, and sugar, but you only tell React to check for flour and eggs, React won't notice when you swap out the sugar. You'll keep getting the old flavor.

Key Takeaway: Every value referenced inside useMemo or useCallback must appear in the dependency array. This ensures React re-runs the memoization when any input changes, preventing stale data bugs.