Compound components
Expose a component's internals as named subcomponents that share state through a private context.
- #react
- #patterns
- #composition
Instead of one component with twenty configuration props, expose a small family of subcomponents that coordinate through context.
The problem with prop explosion
A configurable accordion grows props like headerClassName, renderIcon, iconPosition and hideDivider. Each one guesses at a caller's layout, and none of them compose.
The pattern
The parent owns the open state, and each subcomponent reads it from a private context.
Guarding the context
Throw when a subcomponent renders outside its parent:
An error during development costs one stack trace. A component that renders nothing costs an afternoon.
Trade-offs
- A caller can reorder and wrap the parts, which is the point of the pattern.
- A caller can also build an invalid structure, so the context guard is not optional.
- Static properties on the parent defeat tree-shaking. Export each subcomponent on its own as well.
Related entries
- Render props. The alternative when a caller needs the state value itself.
- Headless data table. Built from this pattern.
Related entries
Render props
Hand rendering control to the caller through a function child, and when a hook is the better answer.
Error boundaries
Keep a render-time failure inside one subtree, and recover from it without a full page reload.
useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.