React › Design Patterns in React
What is the compound component pattern in React, and when is it useful?
AdvancedAnswer
Compound components let several related components work together and share hidden state behind the scenes, while still letting the person using them arrange the pieces however they like. A common example is a set of Tabs and Tab components that automatically know which tab is currently active without the parent needing to manage that manually.
function Tabs({ children }) {
const [activeIndex, setActiveIndex] = useState(0);
return React.Children.map(children, (child, index) =>
React.cloneElement(child, { isActive: index === activeIndex, onSelect: () => setActiveIndex(index) })
);
}
function Tab({ label, isActive, onSelect }) {
return <button onClick={onSelect} style={{ fontWeight: isActive ? 'bold' : 'normal' }}>{label}</button>;
}Real-world example A component library builds a Tabs and Tab set using the compound component pattern, letting developers freely arrange and style each tab however they want, while the tabs still correctly share which one is currently selected.