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

Creating a Private Context for Compound Components

Setting up createContext with a compound component-specific API that siblings can subscribe to.

Creating a Private Context for Compound Components

You'll learn how to build a private communication channel between compound component siblings using React Context.

The Communication Problem

When you have compound components like <Tabs>, <TabList>, and <TabPanel>, they need to coordinate state (which tab is active?) without forcing users to pass props everywhere. You need an invisible wire connecting siblings that users never see or configure.

Setting Up a Private Context

Create a context that lives only within your compound component file — users should never import or touch it directly:

import { createContext, useContext, useState } from 'react';

// Private — not exported!
const TabsContext = createContext(null);

function Tabs({ children }) {
  const [activeTab, setActiveTab] = useState(0);
  
  // Provide shared state to all children
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  );
}

function TabList({ children }) {
  const { activeTab } = useContext(TabsContext);
  // Use activeTab to style tabs
  return <div>{children}</div>;
}

function Tab({ index, children }) {
  const { activeTab, setActiveTab } = useContext(TabsContext);
  // Subscribe to shared state
  return (
    <button onClick={() => setActiveTab(index)}>
      {children}
    </button>
  );
}

The Key Pattern

  1. Don't export the context — keep it module-private
  2. Parent provides — the root component (Tabs) wraps children with Provider
  3. Siblings subscribe — child components (Tab, TabPanel) call useContext to tap into shared state
  4. Users see magic — from their perspective, components "just work" together

Key Takeaway: A private context lets compound components share state internally without polluting your public API — parent provides, siblings subscribe, users stay blissfully unaware of the wiring.