Sub topic 2
Compound Components: The Idea
This chapter assumes you know function components, JSX, props, useState, event handlers, and ES module syntax.
Compound components: the idea
A compound component is a group of related components that work together through shared state. The parent owns the behavior, while the consumer chooses the structure and order of the child components.
This approach is useful when a component needs flexible markup. A Tabs component, for example, can expose Tabs.Tab and Tabs.Panel instead of requiring many configuration props.
<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>The consumer controls layout. Tabs controls which value is active.
Building compound components with context
React context shares a value with descendants without passing props through every intermediate component. A compound component commonly stores its state in context.
import { createContext, useContext, useState } from 'react';
const TabsContext = createContext(null);
function useTabs() {
const context = useContext(TabsContext);
if (!context) {
throw new Error('Tabs components must be inside <Tabs>');
}
return context;
}
export function Tabs({ defaultValue, children }) {
const [value, setValue] = useState(defaultValue);
return (
<TabsContext.Provider value={{ value, setValue }}>
{children}
</TabsContext.Provider>
);
}
function Tab({ value, children }) {
const { value: active, setValue } = useTabs();
return (
<button
role="tab"
aria-selected={active === value}
onClick={() => setValue(value)}
>
{children}
</button>
);
}
function Panel({ value, children }) {
const { value: active } = useTabs();
return active === value ? (
<div role="tabpanel">{children}</div>
) : null;
}
Tabs.Tab = Tab;
Tabs.Panel = Panel;Attaching subcomponents and guarding misuse
Assignments such as Tabs.Tab = Tab create a readable namespace. The useTabs guard fails early when someone renders Tabs.Tab outside Tabs. Without that check, the component might fail later with a less useful error.
Props as slots
A slot is a prop whose value supplies a piece of UI. The children prop is the most common slot, but named slots can clarify intent:
function Card({ title, actions, children }) {
return (
<section>
<header>
<h2>{title}</h2>
{actions}
</header>
<div>{children}</div>
</section>
);
}Slots provide composition without shared state. Use compound components when related parts must coordinate; use slots when the parent only needs places to render caller-provided content.
Exercise
When should you prefer a compound component over several independent components with props?
Show answer
Prefer it when related components need shared behavior or state and consumers need control over their markup.