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

Solution 1: useMemo the Context Value

Wrap the value object in useMemo with proper dependencies to maintain stable reference between renders.

Solution 1: useMemo the Context Value

What You'll Learn

You'll learn how to use useMemo to prevent unnecessary re-renders by keeping your Context value reference stable between renders.

The Core Problem Recap

When you write <MyContext.Provider value={{ user, setUser }}>, React creates a brand new object on every render. Even if user and setUser haven't changed, that new object has a different reference, so all Context consumers re-render unnecessarily.

The useMemo Solution

Wrap your Context value object in useMemo. This creates the object once and only recreates it when its dependencies actually change:

function UserProvider({ children }) {
  const [user, setUser] = useState(null);

  // Memoize the value object
  const value = useMemo(() => {
    return { user, setUser };
  }, [user]); // Only recreate when user changes

  return (
    <UserContext.Provider value={value}>
      {children}
    </UserContext.Provider>
  );
}

Why This Works

useMemo compares dependencies ([user] here) between renders. If user hasn't changed, it returns the same object reference from last time. Consumers get the same value object, so React knows nothing changed and skips their re-renders.

Dependency Array Rules

Include values that actually change in your dependencies. In this example, setUser is stable (doesn't change between renders), so we only need user. If you have multiple changing values, include them all: [user, theme, settings].

Analogy

Think of it like reusing the same lunch box every day instead of buying a new one. The contents might change (your sandwich), but if they haven't, why replace the box? Consumers check the box reference first—if it's the same box, they don't even look inside.

Key Takeaway: Wrapping your Context value in useMemo with proper dependencies prevents object recreation on every render, keeping references stable and avoiding unnecessary consumer re-renders.