Course contentsShow
← React
Lesson 856 of 2,39622. Context PerformanceFree lesson

The useMemo Dependency Array Trap in Context

If dependencies change frequently, useMemo won't help; you need architectural changes like splitting context.

The useMemo Dependency Array Trap in Context

You'll learn why useMemo becomes ineffective when context dependencies change too frequently, and when you need architectural changes instead.

The Problem with Frequent Changes

You've learned to use useMemo to stabilize context values and prevent unnecessary re-renders. But here's the trap: useMemo only helps if its dependencies stay stable. When dependencies change frequently, useMemo recalculates the value on every change anyway—you've gained nothing except extra code complexity.

When useMemo Stops Being a Solution

Imagine a context that provides user data, theme settings, and notification count—all in one object:

const value = useMemo(
  () => ({ user, theme, notificationCount }),
  [user, theme, notificationCount]
);

If notificationCount updates every few seconds, the entire context value changes constantly. Every consumer re-renders, even if they only care about user. The useMemo hasn't solved anything—it's just window dressing on a fundamental architecture problem.

The Real Solution: Split the Context

When dependencies change frequently, you need architectural changes, not performance tricks. Split your context into separate concerns:

  • One context for stable user data
  • One context for theme (changes rarely)
  • One context for notifications (changes frequently)

Now only notification consumers re-render when the count updates. Components that just need user info remain unaffected.

Think Architecture First, Optimization Second

useMemo is a band-aid for occasional object creation. It cannot fix a poorly designed context structure. If you find yourself fighting frequent dependency changes, step back and ask: "Should these values even be in the same context?"

Key Takeaway: When useMemo dependencies change frequently, the hook provides no benefit—you need to split your context into separate providers based on update frequency and consumer needs.