React Patterns & Best PracticesEntry 1 of 10

Compound Components: The Idea

Compound components are several components that only work together and share state internally, like <select> and <option> in HTML.

Notes

  • A single configurable component (<Accordion items={[...]} />) ends up with many props to control every detail of each item.
  • A compound version hands the structure back to the consumer:
<Accordion>  <Accordion.Item id="experience">    <Accordion.Title>We got 20 years of experience</Accordion.Title>    <Accordion.Content>...</Accordion.Content>  </Accordion.Item></Accordion>
  • The parent owns the shared state (which item is open). Children read it through Context, so the consumer never wires state or props between them.
  • Each child is useless on its own and should throw a clear error if used outside its parent.

What / Why / When

What

A family of components sharing hidden state.

Why

Flexible markup and content without a huge props API.

When

Accordions, tabs, menus, dropdowns, steppers: UI made of related parts.

Angular

The same pattern is built with content projection (<ng-content />) and DI: child components inject() their parent component to reach shared state. Angular Material's tabs and expansion panels use this pattern.

Quick reference

ConcernReactAngular
Render consumer markupchildren<ng-content />
Shared stateContext in the parentSignals in the parent component
Child reads stateuseContext() / use()inject(ParentComponent)