What are compound components in React
· Category: React
Short answer
Compound components are a set of components that work together to form a complete UI, sharing implicit state through React Context or a parent component.
How it works
A parent component manages state and provides it to child components via Context. Each child is exported as a static property of the parent, allowing an expressive JSX structure.
Example
function Tabs({ children }) {
const [active, setActive] = useState(0);
return <TabsContext.Provider value={{ active, setActive }}>{children}</TabsContext.Provider>;
}
Tabs.Panel = function Panel({ index, children }) {
const { active } = useContext(TabsContext);
return active === index ? <div>{children}</div> : null;
};
Why it matters
This pattern creates flexible APIs where consumers compose pieces declaratively. It is used in libraries like Reach UI and Radix Primitives.