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?

WithoutWith Compound Components
Giant config prop <Tabs items={[...]}Declarative composition
Hard to customize individual itemsFull control over each child
Rigid APIFlexible, composable API
Tight couplingLoose coupling

Approaches

ApproachMechanismFlexibility
Context-basedcreateContext + ProviderMost flexible, any nesting depth
React.ChildrenIterate/clone childrenOnly direct children

File

  • compound.tsx — Tabs, Accordion, Menu, Toggle Group — all using compound component pattern with Context