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

Implementing Shared State Logic

Add state management in the parent that child components can read and update through context.

Implementing Shared State Logic

What you'll learn: How to add state management in the parent component that all child components can access and modify through context.

The Missing Piece: Making It Interactive

You've set up your compound component architecture with context for communication. Now it's time to make it actually do something. This is where you add the shared state that coordinates behavior across all child components.

Think of it like a thermostat system in a building. The control panel (parent) holds the current temperature setting (state). Any room's sensor (child component) can read that setting, and any room's dial (another child) can adjust it. Everyone sees the same temperature because they're all connected to the central system.

Adding State to the Parent

In your parent component's body, you'll use hooks like useState to create the state you need. Then, you pass both the state values and the updater functions into the context provider:

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

  const contextValue = {
    activeTab,
    setActiveTab
  };

  return (
    <TabsContext.Provider value={contextValue}>
      {children}
    </TabsContext.Provider>
  );
}

Now any child component using useTabsContext() can access activeTab to render conditionally, or call setActiveTab to switch tabs—all without passing props manually through the tree.

The Power of Encapsulation

This pattern keeps your state logic private to the compound component family. Users of your component don't need to manage this state themselves; it's handled internally. They just compose the pieces, and the coordination happens automatically.

Key Takeaway: Shared state logic in compound components means adding useState (or other hooks) in the parent and distributing both state and setters through context, enabling coordinated behavior without prop drilling.