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

When Array Values Need useMemo

Arrays also have reference identity, so [value1, value2] must be memoized or will cause re-renders.

When Array Values Need useMemo

What you'll learn: You'll discover why passing arrays directly to Context triggers unnecessary re-renders and when you must wrap them with useMemo.

The Reference Identity Problem with Arrays

You already know that objects created inline (like {{ user, setUser }}) cause all Context consumers to re-render because JavaScript creates a new object reference on every render. Arrays have the exact same problem.

When you write [value1, value2] inside a component, JavaScript creates a brand-new array with a new identity every time that component renders—even if value1 and value2 haven't changed.

// ❌ Creates a NEW array on every render
<MyContext.Provider value={[todos, filter]}>
  {children}
</MyContext.Provider>

Every consumer of MyContext sees a "different" array each render and re-renders unnecessarily, even when the actual todo list and filter values are identical.

The useMemo Solution

Wrap your array in useMemo with the array's contents as dependencies. React will only create a new array when those dependencies actually change:

// ✅ Same array reference until todos or filter changes
const contextValue = useMemo(() => [todos, filter], [todos, filter]);

<MyContext.Provider value={contextValue}>
  {children}
</MyContext.Provider>

Now consumers only re-render when todos or filter genuinely update, not on every parent render.

When to Apply This

Use useMemo for arrays in Context when:

  • The array contains state or derived values
  • Multiple components consume this Context
  • You notice performance issues in DevTools Profiler

Don't bother if your array contents change on every render anyway—memoization won't help.

Key Takeaway: Arrays have reference identity just like objects. Always wrap Context arrays with useMemo to prevent re-rendering all consumers on every render.