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

The Provider Pattern in Parent Components

Wrapping children with Context.Provider to expose shared state and controls to compound component children.

The Provider Pattern in Parent Components

What you'll learn: How to wrap compound component children with Context.Provider so they can all access shared state and controls without prop drilling.

The Core Idea

Once you've created a private Context for your compound components, the parent component needs to actually provide that shared state to its children. This is where the Provider pattern comes in: you wrap the children prop with <YourContext.Provider value={...}>, passing down whatever state, functions, or controls the child components need.

Think of it like a Wi-Fi router. The parent component is the router that broadcasts the signal (state + controls). The compound children are devices that connect to that signal. Without wrapping children in the Provider, it's like having a router that's unplugged—the devices have no way to access the network.

How It Works

The parent component:

  1. Creates local state (usually with useState)
  2. Defines any helper functions or controls
  3. Wraps its children with <Context.Provider>
  4. Passes an object containing state and controls to the value prop
function Tabs({ children }) {
  const [activeTab, setActiveTab] = useState(0);
  
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div className="tabs">
        {children}
      </div>
    </TabsContext.Provider>
  );
}

Now any compound child (<Tabs.Panel>, <Tabs.Tab>, etc.) can consume TabsContext and access both activeTab and setActiveTab without receiving them as props.

Key Takeaway: The Provider pattern wraps compound component children with Context.Provider, exposing shared state and controls to all descendants without explicit prop passing—making compound components feel connected and coordinated.