Sub topic 7
Compound Components: The Idea
A compound component is a set of components that work together as one unit. The parent owns the state. The children read and change that state without the consumer wiring props between them. This chapter explains the idea and the problem it solves. The next chapter builds one with context.
This chapter assumes you know function components, props, JSX, useState, and how to pass functions as props. It also assumes you have read the earlier chapters on composition and lifting state.
The problem: configuration props
Suppose you build a tabs widget. The first design most people reach for is a single component with a configuration prop.
import { useState } from 'react';
export function Tabs({ items, defaultValue }) {
const [value, setValue] = useState(defaultValue);
const current = items.find((item) => item.value === value);
return (
<div>
<div role="tablist">
{items.map((item) => (
<button
key={item.value}
role="tab"
aria-selected={item.value === value}
onClick={() => setValue(item.value)}
>
{item.label}
</button>
))}
</div>
<div role="tabpanel">{current?.content}</div>
</div>
);
}It works, and the usage is short:
<Tabs
defaultValue="one"
items={[
{ value: 'one', label: 'One', content: 'First panel' },
{ value: 'two', label: 'Two', content: 'Second panel' },
]}
/>The trouble starts when requirements grow. A consumer wants an icon in one tab. Another wants a disabled tab. Another wants the tab list below the panel. Each request adds a field to items or a new prop such as tabListPosition, renderLabel, or isDisabled. The component becomes a long list of options, and each option is a decision the author made on the consumer's behalf.
The idea: split the component and share state implicitly
A compound component splits the widget into pieces that the consumer arranges. Compare the usage:
<Tabs defaultValue="one">
<div role="tablist">
<Tabs.Tab value="one">One</Tabs.Tab>
<Tabs.Tab value="two">Two</Tabs.Tab>
</div>
<Tabs.Panel value="one">First panel</Tabs.Panel>
<Tabs.Panel value="two">Second panel</Tabs.Panel>
</Tabs>Three things are different:
- The consumer writes the markup. Putting an icon in a tab, adding a wrapper
div, or moving the tab list below the panels needs no new prop. - The pieces have no props that connect them.
Tabs.TabandTabs.Panelshare only avaluethat identifies them. Neither receives the selected value or a setter from the consumer. - The pieces are only meaningful together, like
<select>and<option>in HTML. An<option>outside a<select>does nothing useful.
The select and option comparison is the usual mental model. You never pass <option> the index of the selected item. The browser's select tracks that internally, and the options take part in it.
How the pieces share state
There are two common ways to share state between a parent and its children without the consumer's help.
| Approach | How it works | Limitation |
|---|---|---|
| `React.Children` and `cloneElement` | The parent walks `props.children` and injects extra props into each child element. | Only works for direct children. A wrapper `div` breaks it. |
| Context | The parent provides state through a context provider. Any descendant reads it with `useContext`. | Needs a guard for use outside the parent. |
The cloning approach looks like this:
import { Children, cloneElement, useState } from 'react';
export function Toggle({ children }) {
const [on, setOn] = useState(false);
return Children.map(children, (child) =>
cloneElement(child, { on, toggle: () => setOn((prev) => !prev) })
);
}This is simple, but it is fragile. If the consumer wraps a child in a div, or if a child is a string or a fragment, the injected props land on the wrong element or on none. In the tabs example above, the consumer wraps the tabs in <div role="tablist">, which cloning could not support. Context solves this because it reaches any depth. The tutorial uses context from here on, and the next chapter builds it.
What the parent is responsible for
In a compound component, the parent has three jobs:
- Own the state. In
Tabs, that is the selectedvalue. - Expose that state and the ways to change it to its descendants.
- Render the wrapper element, if any.
Each subcomponent has a narrower job. Tab renders a button and reports clicks. Panel decides whether to render its content. Neither stores the selection itself. If they did, they could disagree with each other, which is the problem lifting state up already solved.
This is the relationship to earlier chapters. Lifting state up places state in a common ancestor but makes the consumer pass props down by hand. Compound components keep the ancestor as the owner but hide the passing inside the component family.
When it fits
Compound components suit UI where several parts must stay in sync and the consumer wants layout control:
- Tabs, accordions, menus, and dropdowns
- Modal with header, body, and footer
- Radio groups and form field wrappers
- Tables with sortable headers
They fit less well when the consumer needs almost no customization. A button that takes a label and a click handler gains nothing from being split into parts.
Costs and edge cases
The flexibility has a price. Know these before you adopt the pattern.
- Consumers can arrange pieces incorrectly. A
Tabs.Tabrendered outsideTabshas no state to read. Guard against it with a clear error, as covered in the chapter on attaching subcomponents and guarding misuse. - More surface area to document. One component with props becomes several components, and the valid combinations must be explained.
- Matching is by convention. In the tabs example, a
Tabwithvalue="one"and aPanelwithvalue="one"belong together only because the strings match. A typo produces a tab with no panel, and nothing warns you. - Every consumer of the context re-renders when it changes. With the tabs example, all tabs and panels re-render when the selection changes. For small widgets this is fine. For very large lists, measure before optimizing.
- Accessibility is now partly the consumer's job. The consumer places the
tablistwrapper. If they forget it, the roles are incomplete. A later chapter covers how to reduce this risk.
A quick check on the idea
Before moving on, look at the finished usage again and identify what the consumer does not do. They do not hold the selected value in state, they do not pass onClick to the tabs, and they do not tell panels whether they are visible. All of that is hidden in the component family. That hidden coordination is the defining feature of the pattern.
Exercise
A teammate's Accordion takes an items prop and a renderHeader prop, and now requests a headerPosition prop and an iconForItem prop. Describe how a compound component version would handle both requests without new props, and name one risk it introduces.
Show answer
The compound version exposes pieces such as Accordion, Accordion.Item, Accordion.Header, and Accordion.Panel, which share the open item through context. The consumer places the header after the panel to change position, and puts an icon inside Accordion.Header as ordinary JSX. No new props are needed. One risk is that a subcomponent may be used outside Accordion and have no state to read, so it needs a guard. Other acceptable risks are mismatched value strings between header and panel, and more API surface to document.
Exercise
Why does the cloneElement approach fail when a consumer wraps a Toggle child in a div, and why does context avoid the problem?
Show answer
cloneElement adds props only to the elements that are direct children in props.children. If a child is wrapped in a div, the props go to the div, not to the component inside it. Context does not depend on element position. Any descendant at any depth can call useContext and read the provided value.