Advanced Composition Patterns
Patterns are tools for recurring design problems. Use them only when they improve ownership, composition, reuse, testability, API clarity, or isolation of complexity.
Prefer plain composition firstโ
function Panel({ title, children }) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}
Compound componentsโ
<Menu>
<Menu.Trigger>Account</Menu.Trigger>
<Menu.Content>
<Menu.Item>Profile</Menu.Item>
<Menu.Item>Log out</Menu.Item>
</Menu.Content>
</Menu>
Keep internal coordination private when consumers do not need it.
Controlled and uncontrolled APIsโ
function Toggle({ pressed, defaultPressed = false, onPressedChange }) {
const [internal, setInternal] = useState(defaultPressed);
const isControlled = pressed !== undefined;
const value = isControlled ? pressed : internal;
function setValue(next) {
if (!isControlled) setInternal(next);
onPressedChange?.(next);
}
return <button aria-pressed={value} onClick={() => setValue(!value)} />;
}
Switching between the two modes during the same lifetime is usually a bug.
Reducers model explicit transitionsโ
type State =
| { status: 'closed' }
| { status: 'opening' }
| { status: 'open' }
| { status: 'closing' };
type Action =
| { type: 'OPEN' }
| { type: 'OPENED' }
| { type: 'CLOSE' }
| { type: 'CLOSED' };
The value of a reducer is not that it stores several fields; it is that events and transitions become explicit.
State reducer patternโ
Some reusable libraries allow consumers to intercept a proposed transition:
<Toggle
stateReducer={(state, action, nextState) => {
if (action.type === 'toggle' && state.locked) return state;
return nextState;
}}
/>
This is powerful but creates a much larger public API surface. Use it only when transition customization is a real requirement.
Hooks vs render propsโ
const { x, y } = useMousePosition();
<DataLoader>
{({ data, pending, error }) => {
if (pending) return <Spinner />;
if (error) return <ErrorView />;
return <Chart data={data} />;
}}
</DataLoader>
Hooks replaced many historical render-prop use cases, but render props are still valid when render structure itself is part of the API.
Higher-order componentsโ
const Enhanced = withPermissions(Component);
HOCs still matter in older codebases and some library/framework APIs. For new application architecture, Hooks and composition are often easier to type, debug, and compose.
Adapter components isolate vendor APIsโ
function ProductChart({ points }) {
return (
<ThirdPartyChart
series={[{ data: points }]}
animation={false}
/>
);
}
The same pattern works for analytics, payments, maps, editors, and provider components.
Headless behavior + styled presentationโ
Do not split behavior and presentation mechanically. Separation is valuable when multiple presentations genuinely share the same interaction contract.
Pattern selection checklistโ
Architectural ruleโ
A pattern earns its complexity when it makes ownership and change easier to reason about than the simpler code it replaces.