HomeReact
Chapter 18
18 — Compound Components
Compound components are a pattern where multiple components work together to form a complete UI, sharing implicit state. Think <select> + <option> in HTML.
The Pattern
<Accordion>
<Accordion.Item value="faq1">
<Accordion.Trigger>Question 1</Accordion.Trigger>
<Accordion.Content>Answer 1</Accordion.Content>
</Accordion.Item>
</Accordion>Why?
| Without | With Compound Components |
|---|---|
Giant config prop <Tabs items={[...]} | Declarative composition |
| Hard to customize individual items | Full control over each child |
| Rigid API | Flexible, composable API |
| Tight coupling | Loose coupling |
Approaches
| Approach | Mechanism | Flexibility |
|---|---|---|
| Context-based | createContext + Provider | Most flexible, any nesting depth |
React.Children | Iterate/clone children | Only direct children |
File
compound.tsx— Tabs, Accordion, Menu, Toggle Group — all using compound component pattern with Context