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

The Mental Model: Cache Invalidation

Thinking of memoized values as cached until dependencies change, then recomputed and cached again with new dependencies.

The Mental Model: Cache Invalidation

You'll learn: How to think about useMemo and useCallback as a cache that automatically refreshes when its inputs change.

Understanding Memoization as Caching

The best way to understand React's memoization hooks is to think of them as a caching system. When you first call useMemo or useCallback, React:

  1. Runs your function (the expensive calculation or the callback you're defining)
  2. Stores the result in memory (the cache)
  3. Watches the dependency array for changes

On subsequent renders, React checks: "Have any dependencies changed?" If not, it returns the cached value instantly—no recalculation needed. If dependencies have changed, React invalidates the cache, runs your function again with the new inputs, and caches this fresh result.

The Analogy

Think of it like a coffee shop keeping your usual order on file. As long as you're "the same person" (same dependencies), they hand you the cached order immediately. But if you change something ("extra shot of espresso" = new dependency value), they invalidate your old order and make a fresh one, which becomes your new cached order.

Why "Invalidation" Matters

Cache invalidation is what keeps your memoized values correct. React doesn't blindly serve stale data—it actively monitors your dependency array. Change a dependency? Cache invalidated. New computation runs. New result cached. This automatic invalidation is why memoization in React is safe and reliable, not a source of bugs.

Key Takeaway: Memoization creates a cache that's automatically invalidated and refreshed whenever dependencies change—you get correct values without manual cache management.