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

Building the Context Provider

Implement the provider that wraps children and manages the compound component's shared state.

Building the Context Provider

What you'll learn: How to implement the provider component that wraps all compound component children and supplies the shared state they need.

The Provider's Role

Now that you have your context created, you need a provider component that actually manages and distributes the shared state. This provider wraps all the compound component's children and makes state available through the context you set up earlier.

Think of it like a Wi-Fi router: the context is the wireless protocol, but the provider is the actual router device that broadcasts the signal. All devices (child components) in range can connect to it.

Implementation Pattern

The provider is typically the parent component itself. It:

  1. Creates and manages state with hooks like useState
  2. Bundles that state (and updater functions) into a context value
  3. Wraps {children} with the Context Provider component

Here's the basic structure:

function Tabs({ children, defaultValue }) {
  const [activeTab, setActiveTab] = useState(defaultValue);

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div className="tabs">
        {children}
      </div>
    </TabsContext.Provider>
  );
}

The provider receives children as a prop and wraps them in TabsContext.Provider, passing the state through the value prop. Any child component can now access activeTab and setActiveTab without explicit prop drilling.

Why This Works

The provider creates a single source of truth for all compound children. Tabs.List, Tabs.Tab, and Tabs.Panel can all consume this context and stay synchronized. When one child calls setActiveTab, all consuming children re-render with the new value automatically.

Key Takeaway: The context provider component wraps children, manages shared state internally, and broadcasts it through the context's value prop—enabling implicit communication between all compound component parts.