Compound components

Intermediate · 18 min

Building components that implicitly share state through context, with a worked Tabs/Tab example, and why it beats a prop-heavy API.

Before thisContext, and avoiding prop drillingComponents and props

Cosden Solutions · 18 min

Compound components

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Cosden SolutionsReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A compound component is a set of components meant to be used together, like <Tabs> and <Tab>, that share state implicitly instead of each piece receiving everything through props.
  • The sharing mechanism is usually a context created inside the parent component, invisible to whoever imports and renders the pair.
  • The payoff is a public API that reads like plain JSX composition, with no large prop object threaded through every child.
  • The parent owns the shared state (such as which tab is active) and exposes it through context; each child reads only the slice it needs.
  • Because the context is created and provided inside the compound component's own file, consumers never have to import or touch it directly.
  • The pattern costs some indirection: a child rendered outside its parent's provider will crash or silently fail, so a clear error message at the context boundary matters.

The prop-heavy version, and why it gets ugly

Here is a tabs component built the straightforward way, with everything passed as props and data:

function Tabs({ tabs, activeId, onSelect }) {
  return (
    <div>
      <div className="tab-list">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => onSelect(tab.id)}
            aria-selected={tab.id === activeId}
          >
            {tab.label}
          </button>
        ))}
      </div>
      <div className="tab-panel">
        {tabs.find((tab) => tab.id === activeId)?.content}
      </div>
    </div>
  );
}

It works, but every tab’s label and content have to live inside a tabs array rather than as plain JSX. Adding an icon to one tab, or conditionally rendering a tab, means reshaping that array instead of just writing or removing JSX elements. The component’s shape doesn’t match how people actually write markup.

Building it as a compound component

A compound Tabs/Tab pair shares the active-tab state through context, created inside the same file:

const TabsContext = createContext(null);

function Tabs({ children, defaultTabId }) {
  const [activeId, setActiveId] = useState(defaultTabId);
  return (
    <TabsContext.Provider value={{ activeId, setActiveId }}>
      <div className="tabs">{children}</div>
    </TabsContext.Provider>
  );
}

function useTabsContext() {
  const context = useContext(TabsContext);
  if (!context) {
    throw new Error("Tab must be rendered inside <Tabs>");
  }
  return context;
}

function TabList({ children }) {
  return <div className="tab-list">{children}</div>;
}

function Tab({ id, children }) {
  const { activeId, setActiveId } = useTabsContext();
  return (
    <button onClick={() => setActiveId(id)} aria-selected={id === activeId}>
      {children}
    </button>
  );
}

function TabPanel({ id, children }) {
  const { activeId } = useTabsContext();
  return activeId === id ? <div className="tab-panel">{children}</div> : null;
}

Tabs.List = TabList;
Tabs.Tab = Tab;
Tabs.Panel = TabPanel;

A consumer writes plain JSX, with no array of tab objects to maintain:

<Tabs defaultTabId="profile">
  <Tabs.List>
    <Tabs.Tab id="profile">Profile</Tabs.Tab>
    <Tabs.Tab id="settings">Settings</Tabs.Tab>
  </Tabs.List>
  <Tabs.Panel id="profile">Profile content here.</Tabs.Panel>
  <Tabs.Panel id="settings">Settings content here.</Tabs.Panel>
</Tabs>

Nothing here passes activeId or setActiveId by hand. Tab and TabPanel each call useTabsContext() to read exactly the slice of shared state they need, and the consumer never sees that context exists. Attaching Tab, TabList, and TabPanel as properties on Tabs (Tabs.Tab, and so on) is a naming convention, not a requirement — it just makes the relationship between the pieces obvious at the call site.

Why this beats a big prop object

Compare the two consumer-facing APIs. The prop-driven version forces every tab’s data into one array the parent owns, so conditional tabs, custom per-tab markup, or an icon next to one label all mean reshaping that array’s item type. The compound version is just JSX: wrap a Tabs.Tab in a condition to render it conditionally, pass whatever children a Tabs.Panel needs, add a prop to one Tab without touching the others. It reads the way the rest of React reads — components nested by composition — rather than as configuration data fed into one component.

The cost is indirection. Someone unfamiliar with the pattern sees <Tabs.Tab> and has to know it secretly depends on a <Tabs> ancestor providing context; the useTabsContext guard that throws a clear error is what makes that failure obvious rather than a cryptic Cannot read properties of null.

What the video covers

Cosden Solutions’ Compound Components in React builds a Tabs-style pair from scratch and shows the context-sharing wiring between the parent and its sub-components step by step, which is the backbone of this lesson’s worked example above. It spends most of its time on the mechanics; the honest trade-off against a prop-driven API, and the importance of a clear error when a child is used outside its parent, get more attention here than in the video itself.

Where this fits

Compound components are one way to share logic between related components. Before hooks, two other patterns did similar jobs for logic shared between unrelated components. Next: render props and higher-order components.

Check yourself

  1. 01What distinguishes a compound component from two components that just happen to be used near each other?

    A compound component's pieces share implicit state — such as which tab is active — through a context that the parent sets up, so the children coordinate without the consumer passing that state between them explicitly.

  2. 02Where does the context that powers a Tabs/Tab pair typically get created?

    Inside the compound component's own module, alongside the Tabs and Tab definitions. It is an implementation detail; the code importing Tabs and Tab never imports or references that context directly.

  3. 03What happens if a <Tab> is rendered outside of a <Tabs> provider?

    Calling useContext inside Tab returns the context's default value, often null or undefined, which typically causes a crash or silently broken behavior when Tab tries to read a property off it. A well-built compound component throws a clear error from inside Tab instead, naming the missing parent.

  4. 04Why does a compound component's public API tend to need fewer props than an equivalent component built with one big prop object?

    Because the state each child needs (which tab is active, how to select a given tab) comes from context rather than from props passed down by the consumer, so the consumer only writes the JSX structure — which Tab elements exist and in what order — rather than wiring data through every layer.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark