Setting Up Internal Context
What you'll learn: How to create a private React context that lets your parent compound component communicate with its children behind the scenes.
The Core Idea
When building compound components, the parent needs to share state and actions with its children—but you don't want to expose that mechanism to external code. Internal context acts as a secret handshake between related components.
Think of it like a private radio channel: only components that belong to your compound family can tune in. Everyone else doesn't even know it exists.
Creating the Private Context
You create the context in the same file as your compound components, but don't export it:
import { createContext } from 'react';
// Private — not exported!
const TabsContext = createContext(null);
This context lives alongside your parent component but remains invisible to consumers of your API.
Why Keep It Private?
By not exporting the context, you prevent external code from:
- Directly accessing internal state
- Breaking your component's encapsulation
- Creating dependencies on implementation details
The parent component will provide the context value, and children will consume it—but users of your <Tabs> component never touch TabsContext directly. They just compose <Tabs.List> and <Tabs.Panel> without worrying about how they communicate.
Example Structure
const TabsContext = createContext(null);
function Tabs({ children }) {
// Will provide context value here
return <TabsContext.Provider>{children}</TabsContext.Provider>;
}
Tabs.List = function TabsList() {
// Will consume context here
};
Key Takeaway: Internal context is your compound component's private communication layer—create it with createContext() but never export it, keeping implementation details hidden while enabling seamless parent-child coordination.