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
- Don't export the context — keep it module-private
- Parent provides — the root component (
Tabs) wraps children withProvider - Siblings subscribe — child components (
Tab,TabPanel) calluseContextto tap into shared state - 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.