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

Passing Actions Through Context

Sharing callbacks and state setters via context so children can trigger parent-level changes.

Passing Actions Through Context

What you'll learn: How to share callbacks and state setters through context so child components in a compound component system can trigger changes at the parent level.

The Problem: Children Need to Act

In compound components, children often need to do something—close a menu, select a tab, toggle an accordion. But they don't hold the state themselves; the parent does. The solution? Pass state setters and callbacks through the same context you're already using for shared state.

Sharing Actions, Not Just Data

When you create your private context for compound components, include functions alongside state values:

type TabsContextValue = {
  activeTab: string;
  setActiveTab: (id: string) => void; // ← Action!
};

const TabsContext = createContext<TabsContextValue | null>(null);

The parent component creates the state and provides both the value and the setter:

function Tabs({ children }: TabsProps) {
  const [activeTab, setActiveTab] = useState('tab1');
  
  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      {children}
    </TabsContext.Provider>
  );
}

Now child components can consume the context and call the action:

function Tab({ id, children }: TabProps) {
  const { activeTab, setActiveTab } = useTabsContext();
  
  return (
    <button onClick={() => setActiveTab(id)}>
      {children}
    </button>
  );
}

Why This Works

Context acts like an invisible prop tunnel. By passing functions through it, you let deeply nested children communicate back to the parent without prop drilling through every layer.

Key Takeaway: Passing callbacks and state setters through context enables child components to trigger parent-level state changes, creating interactive compound components without breaking encapsulation.