Course contentsShow
← React
Lesson 1097 of 2,39628. Composition: Compound ComponentsFree lesson

Compound Components with Multiple Contexts

Splitting state and actions into separate contexts when some children only need part of the API.

Compound Components with Multiple Contexts

You'll learn how to split state and actions into separate contexts so child components can subscribe only to what they need.

The Problem with Single Context

When all compound component state and actions live in one context, every child re-renders whenever any part of that context changes. Imagine a <Tabs> component where the active tab index and a setActive function share one context. Even if a child only needs to call setActive (not read the current index), it still re-renders when the index changes.

The Multiple Context Solution

Split your compound component's API into separate contexts:

// One context for state (changes frequently)
const TabsStateContext = createContext();

// Another for actions (stable, rarely changes)
const TabsActionsContext = createContext();

The parent provides both:

function Tabs({ children }) {
  const [activeIndex, setActiveIndex] = useState(0);
  const actions = useMemo(() => ({ setActiveIndex }), []);
  
  return (
    <TabsStateContext.Provider value={activeIndex}>
      <TabsActionsContext.Provider value={actions}>
        {children}
      </TabsActionsContext.Provider>
    </TabsStateContext.Provider>
  );
}

Child components choose which context they need:

// Only re-renders when activeIndex changes
function TabPanel() {
  const activeIndex = useContext(TabsStateContext);
  // ...
}

// Never re-renders (actions are memoized)
function TabButton() {
  const { setActiveIndex } = useContext(TabsActionsContext);
  // ...
}

Why This Matters

It's like splitting a noisy group chat into focused channels. Not everyone needs to hear every message. Components that only dispatch actions don't care about state changes, and vice versa.

Key Takeaway: Splitting compound component state and actions into separate contexts lets children opt into only the updates they need, reducing unnecessary re-renders while maintaining clean composition.