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

Consuming Context in Child Components

Using useContext in child components to access shared state without receiving it through props.

Consuming Context in Child Components

What you'll learn: How child components in a compound pattern access shared state from context without receiving it as props.

The Core Idea

Once the parent component provides shared state through a context provider, child components need a way to "tap into" that data. This is where useContext comes in. Instead of drilling props through multiple layers, each child component can directly consume the context and pull out exactly what it needs.

Think of it like a radio signal: the parent broadcasts on a specific frequency (the context), and any child component can tune in with the right receiver (useContext) to pick up that signal.

How It Works

Each child component in your compound structure calls useContext with the same context object the parent created. This gives the child immediate access to whatever data the parent is sharing:

const TabContent = ({ value, children }) => {
  const { activeTab } = useContext(TabsContext);
  
  if (activeTab !== value) return null;
  return <div>{children}</div>;
};

The child doesn't need activeTab passed as a prop. It simply reads it directly from context.

The Beauty of Encapsulation

This pattern creates a clean API for consumers of your compound component. Users don't see the internal wiring—they just compose children naturally. Meanwhile, behind the scenes, all the children are silently coordinating through shared context.

Key Takeaway: Child components use useContext to access shared state from the parent's context provider, eliminating the need for explicit prop passing and enabling implicit communication in compound component patterns.