What are compound components in React?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
Compound components are a pattern where multiple components work together to form a complete UI element, sharing implicit state via React Context. Think of HTML's <select> and <option> — they work together through an implicit relationship. React example: <Tabs><Tabs.Tab id="1" label="First" /><Tabs.Content id="1">Content...</Tabs.Content></Tabs>. The Tabs parent manages the active tab state and shares it via Context; Tabs.Tab and Tabs.Content read from that Context. Implementation: Tabs creates a context with the active ID and setter; the sub-components are attached as static properties (Tabs.Tab = TabComponent). Benefits: flexible API — consumers can reorder, omit, or add sub-components; implicit state sharing without prop drilling; great for UI component libraries (modals, tabs, accordions, dropdowns). Vs render props: compound components are more declarative and composable; render props can be more flexible for injecting dynamic content. Libraries like Radix UI heavily use compound components.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex React.js answers easy to follow.
Previous
What is the difference between React.cloneElement and React.createElement?
Next
What is the React.Children API?