Context Memoization in Compound Components
What you'll learn: How to prevent unnecessary re-renders in compound component children by memoizing the context value object.
The Problem with Context Objects
When you provide an object as your context value in compound components, React checks for changes by reference equality. If you create a new object on every render (even with identical contents), React treats it as a "change" and re-renders every child consuming that context.
// ❌ BAD: New object every render
function Tabs({ activeTab, onTabChange, children }) {
return (
<TabsContext.Provider value={{ activeTab, onTabChange }}>
{children}
</TabsContext.Provider>
);
}
Every time Tabs re-renders, { activeTab, onTabChange } is a new object, even if activeTab and onTabChange haven't changed. All Tab and TabPanel children re-render unnecessarily.
The Solution: useMemo
Wrap your context value object in useMemo with appropriate dependencies:
// ✅ GOOD: Stable object reference
function Tabs({ activeTab, onTabChange, children }) {
const value = useMemo(
() => ({ activeTab, onTabChange }),
[activeTab, onTabChange]
);
return (
<TabsContext.Provider value={value}>
{children}
</TabsContext.Provider>
);
}
Now the context value only creates a new object when activeTab or onTabChange actually change. Children only re-render when the data they depend on truly updates.
Think of It Like a Fingerprint
Without memoization, you're giving React a new fingerprint every time—it assumes something changed. With useMemo, you say: "Only give me a new fingerprint when these specific things change."
Key Takeaway: Always memoize context value objects in compound components to prevent re-rendering all children on every parent render—use useMemo with proper dependencies to maintain stable object references.