Compound components pattern for flexible APIs

3748
0

Compound components create flexible, composable APIs by sharing state between parent and child components via context. Instead of passing dozens of props, child components access shared state through context. A Select component might have Select.Trigger, Select.Options, and Select.Option subcomponents that work together. This pattern provides flexibility—consumers can rearrange, style, or extend components—while maintaining encapsulation. I use TypeScript's namespace syntax or dot notation to attach subcomponents. The parent component provides context, and children consume it with useContext. This is the pattern used by libraries like Radix UI and Headless UI for building accessible, customizable component primitives.