Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 132 ยท Advanced Patterns

Compound Components and Slots

Build flexible React components that share hidden state through context. Learn compound components with a Tabs and Accordion, the Children.map trap, accessible wiring and headless hooks.

Some UI elements are not one component but a small family that only makes sense together. A <select> needs its <option> children. A table needs rows and cells. Tabs need a list of tab buttons and a set of panels, and the two halves must always agree about which tab is active.

HTML solves this by letting the parent and its children share meaning implicitly. In React you can do the same with compound components: a group of components that share state behind the scenes, so the person using them writes only the structure they want. This lesson shows why the pattern exists, how to build it with context, the classic Children.map trap, how to wire it up accessibly, and how to take it one step further into a headless hook.

The problem: configuration props

Imagine you build a Tabs component the obvious way, with a configuration prop:

JSX
<Tabs
  items={[
    { id: 'intro', label: 'Intro', content: <p>Welcome</p> },
    { id: 'api', label: 'API', content: <ApiDocs /> },
  ]}
/>

It works, until the requests arrive. Can one tab have an icon? Can another be disabled? Can a badge appear next to the label? Can the panel for "API" be lazy loaded? Every request becomes a new field on the item object (icon, disabled, badge, lazy, renderLabel...). The component grows an ever-bigger options API and you end up re-implementing JSX with objects.

The compound approach flips this. Instead of describing the UI as data, you let the caller write the UI as JSX, and the components cooperate:

JSX
<Tabs defaultValue="intro">
  <Tabs.List>
    <Tabs.Tab value="intro">Intro</Tabs.Tab>
    <Tabs.Tab value="api">API <Badge>new</Badge></Tabs.Tab>
  </Tabs.List>
  <Tabs.Panel value="intro"><p>Welcome</p></Tabs.Panel>
  <Tabs.Panel value="api"><ApiDocs /></Tabs.Panel>
</Tabs>

A badge, an icon or a disabled flag is now just ordinary JSX or an ordinary prop on one part. The caller controls the markup order and the content, and the parent still controls the behavior. This is composition over configuration (see Children and Composition).

How the parts talk: context

How does Tabs.Tab know which tab is active when Tabs is not passing it any props? Through context. The root component owns the state and publishes it; every part reads it with useContext. If you have not met context yet, read Context first.

The recipe has four steps:

  1. Create a context for the shared state.
  2. The root component owns the state and wraps its children in the provider.
  3. Each part calls a small useTabsContext() hook.
  4. Attach the parts to the root (Tabs.Tab = Tab) so they travel together.
A compound Tabs component

Click "API (new)" and the visible panel changes. Tabs never touched Tab or TabPanel directly; the state travelled through the provider. Notice three details:

  • <TabsContext value={...}> is the React 19 way to provide context; older code wrote <TabsContext.Provider value={...}>.
  • useTabsContext throws a helpful error when a part is rendered outside its root. Without this guard, a misplaced <Tabs.Tab> would fail later with a confusing "cannot destructure property of null".
  • Tabs.List = TabList is a plain JavaScript property assignment on a function. It is a naming convention (like <Menu.Item /> from JSX in Depth), not a React feature. Exporting TabsList, TabsTab separately works just as well and is friendlier to tree shaking in some bundlers.

The value object { activeValue, setActiveValue } is created again on every render of Tabs, so every consumer re-renders whenever Tabs does. For a small component family that is fine. Larger ones memoize the value or split state and actions into two contexts; see Context Patterns.

An accordion: many parts, same trick

The same recipe handles a different shape of state. An accordion has items; each item has a header and a body; each item is open or closed. Here the context carries which items are open, and a second, tiny context tells the header and body which item they belong to.

A compound Accordion with two contexts

Open both items: they stay open independently because openIds is a list. To make it a "one at a time" accordion you would change only toggle inside the root, and no caller would need to change. That is the main benefit of the pattern: the behavior lives in one place, the markup lives with the caller.

The caller can also put anything between the parts: wrap an item in a <section>, add a divider between items, render an item conditionally. The parts find each other through context, not through their position in the children list. That is exactly what makes the next technique, the older way of building compound components, fragile.

The Children.map trap

Before context was common, compound components were built by the parent inspecting its children and injecting props into them with Children.map and cloneElement:

JSX
function Toolbar({ children }) {
  return Children.map(children, (child, index) =>
    cloneElement(child, { isFirst: index === 0 })
  );
}

It looks neat and it works for the simplest case. It is also easy to break, because the parent can only see its direct children as elements. The moment a caller wraps a child in a <div>, a fragment, or their own component, the injected props go to the wrapper and the real child never receives them.

cloneElement stops at the wrapper

The first child is a LoudRow, so Group clones that: it hands LoudRow a prop called isFirst, which LoudRow never passes on. The list shows WRAPPED with no (first) mark, and plain (the second child, index 1) has none either, so nobody is marked. Nothing errors and nothing warns: the feature just stops working, which is the worst kind of bug. Had the Row been first, it would have shown plain (first).

Other limits of the Children helpers: they do not look inside fragments (a fragment counts as one child), Children.count includes text nodes, and cloneElement is marked as legacy in the React documentation because it makes data flow hard to follow. Use context unless you only need a purely visual rule that CSS can express (:first-child).

Rule of thumb: if parts must find each other regardless of nesting, use context. If you only need to style the first or last child, use CSS. Reach for Children.map and cloneElement only when a component must change its children's props and you control all callers.

Wiring accessibility

A compound component is a good place to hide ARIA details, because the person using <Tabs.Tab> should not have to remember them. Real tabs need:

  • role="tablist" on the container, role="tab" on each button, role="tabpanel" on each panel.
  • aria-selected on tabs, and aria-controls / aria-labelledby linking a tab to its panel.
  • Only the active tab in the tab order (tabIndex={0}); the others use -1 and are reached with the arrow keys.

The links between a tab and its panel need ids that match. Hard coding ids from a value prop works, but two Tabs on one page could clash. useId gives each root a unique prefix. (The id strings themselves are opaque; never depend on their exact shape.)

Accessible tabs with arrow keys

Click into the "One" tab and press the right arrow: focus and selection move to "Two", wrapping around after "Three". Screen readers announce "tab, selected, 2 of 3" because the roles and aria-selected are correct, and the panel keeps its content mounted but hidden, so the aria-controls target always exists. Notice that hidden keeps panel state (for example text in a form inside the panel) alive, while returning null, as in the first example, discards it. Choose deliberately: keeping panels mounted costs memory but preserves state.

More on this in Accessibility in React.

Going headless

The Tabs above ship with an opinion about markup (a div list, button tabs). A headless component supplies behavior and accessibility but no markup or styles, so every project can dress it differently. Libraries such as Radix UI, Headless UI and React Aria work this way. You can build the same idea with a hook that returns prop getters: functions producing the props you spread onto your own elements.

A headless useTabs hook

This demo renders tabs as links just to prove that the hook does not care about the element type. Real headless libraries also merge the caller's own onClick with theirs (the example overrides it, then calls the hook's handler by hand) and handle keyboard and ids. The trade-off against compound components: a headless hook gives total control but more wiring per use; compound components give a ready-made structure with less code. Many libraries offer both: a hook at the bottom, a compound component built on top of it.

Design notes and pitfalls

  • Name the parts by role. Tabs.List, Tabs.Tab, Tabs.Panel read like a sentence. If a part has no meaning outside the root, it should only be reachable through the root's namespace.
  • Support controlled and uncontrolled use. Offer both defaultValue and value + onValueChange, as native inputs do. See Controlled vs Uncontrolled Components.
  • Validate structure with errors, not silence. The useTabsContext guard is cheap and saves hours of debugging.
  • Do not overdo it. A card with a header and a footer is perfectly served by children and two slot props. Compound components pay off when the parts need shared state or behavior.
  • Slots are props. When the caller only needs to fill two or three named regions, accept JSX through props instead: <Card header={...} footer={...}>. Compound components are the next step when the regions need to talk to each other.
  • Mind the render cost. One context value shared by many parts re-renders all of them on any change; split the context if profiling shows a problem (Profiling).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main idea behind compound components?

    Compound components cooperate through shared state (usually context) while the caller writes the structure as ordinary JSX, avoiding a growing options object.
  2. 2. Why is context usually better than Children.map plus cloneElement for compound components?

    cloneElement can only change the elements the parent sees. A wrapper receives the injected props instead of the intended child, and nothing warns you. Context works at any depth.
  3. 3. What does useTabsContext do when it throws if the context value is null?

    The default context value is null, so a part rendered outside <Tabs> would otherwise fail with a confusing message later. The guard turns it into a readable error.
  4. 4. In the accessible Tabs example, why do inactive tabs use tabIndex={-1}?

    This roving tabindex pattern keeps one tab stop for the whole tab list; arrow keys move focus inside it, as users expect from native widgets.
  5. 5. What distinguishes a headless component or hook?

    Headless means the logic is packaged without an opinion about elements or CSS. Prop getters or compound parts let each project render its own design.

Summary

  • Compound components are a family of components that share state implicitly, so callers compose the structure in JSX instead of passing a configuration object.
  • The standard recipe: a context, a root that owns the state, parts that read it with a guarded hook, and optional Root.Part namespacing.
  • Avoid Children.map plus cloneElement for this job: wrappers and fragments silently break it.
  • Hide ARIA roles, ids (from useId) and keyboard handling inside the parts so every caller gets accessible widgets for free.
  • Headless hooks that return prop getters give maximum flexibility; compound components give convenience.
  • Support both controlled and uncontrolled use, and use the pattern only when the parts really need shared behavior.

Next: Render Props, Higher-Order Components and Hooks