| 1 | --- |
| 2 | title: Use Compound Components |
| 3 | impact: HIGH |
| 4 | impactDescription: enables flexible composition without prop drilling |
| 5 | tags: composition, compound-components, architecture |
| 6 | --- |
| 7 | |
| 8 | ## Use Compound Components |
| 9 | |
| 10 | Structure complex components as compound components with a shared context. Each |
| 11 | subcomponent accesses shared state via context, not props. Consumers compose the |
| 12 | pieces they need. |
| 13 | |
| 14 | **Incorrect (monolithic component with render props):** |
| 15 | |
| 16 | ```tsx |
| 17 | function Composer({ |
| 18 | renderHeader, |
| 19 | renderFooter, |
| 20 | renderActions, |
| 21 | showAttachments, |
| 22 | showFormatting, |
| 23 | showEmojis, |
| 24 | }: Props) |
| 25 | return ( |
| 26 | <form> |
| 27 | {renderHeader?.()} |
| 28 | <Input /> |
| 29 | {showAttachments && <Attachments |
| 30 | {renderFooter ? ( |
| 31 | renderFooter() |
| 32 | ) : ( |
| 33 | <Footer> |
| 34 | {showFormatting && <Formatting |
| 35 | {showEmojis && <Emojis |
| 36 | {renderActions?.()} |
| 37 | </Footer> |
| 38 | )} |
| 39 | </form> |
| 40 | ); |
| 41 | } |
| 42 | ``` |
| 43 | |
| 44 | **Correct (compound components with shared context):** |
| 45 | |
| 46 | ```tsx |
| 47 | const ComposerContext = createContext |
| 48 | |
| 49 | function ComposerProvider({ children |
| 50 | return <ComposerContext |
| 51 | } |
| 52 | |
| 53 | function ComposerFrame({ children |
| 54 | return <form>{ |
| 55 | } |
| 56 | |
| 57 | function ComposerInput() { |
| 58 | const { |
| 59 | state, |
| 60 | actions: { update |
| 61 | meta: { inputRef |
| 62 | } = use(ComposerContext |
| 63 | return ( |
| 64 | <TextInput |
| 65 | ref={inputRef} |
| 66 | value={state.input |
| 67 | onChangeText={(text) |
| 68 | /> |
| 69 | ); |
| 70 | } |
| 71 | |
| 72 | function ComposerSubmit() { |
| 73 | const { |
| 74 | actions: { submit |
| 75 | } = use(ComposerContext |
| 76 | return <Button |
| 77 | } |
| 78 | |
| 79 | // Export as compound component |
| 80 | const Composer = { |
| 81 | Provider: ComposerProvider, |
| 82 | Frame: ComposerFrame, |
| 83 | Input: ComposerInput, |
| 84 | Submit: ComposerSubmit, |
| 85 | Header: ComposerHeader, |
| 86 | Footer: ComposerFooter, |
| 87 | Attachments: ComposerAttachments, |
| 88 | Formatting: ComposerFormatting, |
| 89 | Emojis: ComposerEmojis, |
| 90 | }; |
| 91 | ``` |
| 92 | |
| 93 | **Usage:** |
| 94 | |
| 95 | ```tsx |
| 96 | <Composer.Provider state={ |
| 97 | <Composer.Frame> |
| 98 | <Composer.Header /> |
| 99 | <Composer.Input /> |
| 100 | <Composer.Footer> |
| 101 | <Composer.Formatting /> |
| 102 | <Composer.Submit /> |
| 103 | </Composer.Footer> |
| 104 | </Composer.Frame> |
| 105 | </Composer.Provider> |
| 106 | ``` |
| 107 | |
| 108 | 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. |