--- title: Use Compound Components impact: HIGH impactDescription: enables flexible composition without prop drilling tags: composition, compound-components, architecture --- ## Use Compound Components Structure complex components as compound components with a shared context. Each subcomponent accesses shared state via context, not props. Consumers compose the pieces they need. **Incorrect (monolithic component with render props):** ```tsx function Composer({ renderHeader, renderFooter, renderActions, showAttachments, showFormatting, showEmojis, }: Props) { return (
{renderHeader?.()} {showAttachments && } {renderFooter ? ( renderFooter() ) : (
{showFormatting && } {showEmojis && } {renderActions?.()}
)} ) } ``` **Correct (compound components with shared context):** ```tsx const ComposerContext = createContext(null) function ComposerProvider({ children, state, actions, meta }: ProviderProps) { return ( {children} ) } function ComposerFrame({ children }: { children: React.ReactNode }) { return
{children}
} function ComposerInput() { const { state, actions: { update }, meta: { inputRef }, } = use(ComposerContext) return ( update((s) => ({ ...s, input: text }))} /> ) } function ComposerSubmit() { const { actions: { submit }, } = use(ComposerContext) return } // Export as compound component const Composer = { Provider: ComposerProvider, Frame: ComposerFrame, Input: ComposerInput, Submit: ComposerSubmit, Header: ComposerHeader, Footer: ComposerFooter, Attachments: ComposerAttachments, Formatting: ComposerFormatting, Emojis: ComposerEmojis, } ``` **Usage:** ```tsx ``` Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.