Compound Components Pattern Explained
Compound Components Pattern Explained
1. What Are Compound Components?
In native HTML, certain elements work together as a synchronized family to provide an intuitive, declarative interface. The classic example is <select> and <option>:
Notice how:
- The
<select>manages the selected state and keyboard navigation. - The
<option>tags configure individual items. - You don't have to pass an awkward configuration object like
<select options={[{label: 'React', value: 'react'}]} />. - You can freely rearrange the options, insert dividing
<hr />elements, or add custom styling between options without breaking functionality.
In React, the Compound Components Pattern replicates this declarative, flexible relationship for custom UI primitives (such as Tabs, Accordions, Dropdown Menus, and Radio Groups).
2. Implementing Compound Components with React Context
To build compound components, a parent component creates a React Context to share state and updater functions with its child components implicitly.
Let's build a compound Tabs component:
3. Beautiful, Declarative Consumer Experience
Consumers of compound components enjoy an elegant, self-describing API:
4. Key Architectural Benefits
- Implicit State Sharing: The consumer never has to manually wire
activeTaboronClickto each individual button; the context handles it automatically. - Extreme Layout Flexibility: The consumer can reorder tabs, nest tabs inside custom grid wrappers, or insert header graphics between elements without breaking state sync.
- Inversion of Control: The consumer dictates the visual hierarchy and layout, while the compound components manage interaction logic and accessibility.
Practice Quiz
Tabs.Tab = Tab)?<Tabs items={dataArray} />?<Tabs.Panel id="backend"> if the active tab is "frontend"?Race Conditions and Stale Closures in useEffect
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Higher-Order Components vs Modern Hooks | Race Conditions and Stale Closures in useEffect |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.