createStyledContext()
Share variant props across compound components
createStyledContext() passes variant props through every styled component in
a compound component tree.
Compound component APIs let related elements coordinate their props:
Setting size="lg" on the outer Button frame should pass down to the Text so the frame and text sizes stay aligned, without requiring explicit size props on every child component.
createStyledContext() provides this coordination for styled components, sharing variant props through React context.
You can set it up as follows:
A few things to note here:
- ButtonContext should only be typed and given properties that work across both components. Since both define a
sizevariant, this works, even though the frame and text read different token scales. - You can use
<Button.Props size="lg"><Button /></Button.Props>now to set default props for a Button from above. - The context pattern currently skips compiler flattening. Avoid using it on low-level primitives like generic Stacks or Text. For higher-level controls like Button, it works well: the compiler still extracts CSS and optimizes render logic.