Sub topic 17
Choosing a Pattern and Its Trade-offs
Prerequisites and goal
This chapter assumes you have met each pattern from the earlier chapters: composition with children, lifting state, render props, higher-order components (HOCs), custom hooks, context, compound components, controlled and uncontrolled modes, control props, prop getters, the state reducer, and headless components. It does not teach them again. It gives you criteria for picking one, and it lists the costs that show up later.
Every pattern trades flexibility for complexity. A more flexible pattern lets consumers do more without changing your code, but it gives you more API surface to document, test, and keep stable. Pick the least flexible pattern that solves the problem you actually have.
Start with the cheapest tool
Work down this list and stop at the first option that fits.
- Plain props. If a component needs a label and a click handler, pass them as props.
- Composition with
childrenor slot props. If the consumer needs to place their own content inside your layout, acceptchildrenor named props such asheaderandfooter. - Lifting state. If two siblings need the same value, move the state to their nearest common parent.
- A custom hook. If several components need the same stateful logic but different markup, extract the logic into a hook.
- Context or a compound component. If state must reach deeply nested parts, or a parent and its children must coordinate while the consumer controls the markup, share state through context.
- Control props, a state reducer, prop getters. Add these only when real consumers need to override your component's behavior.
Most components never need to go past step 3. Moving down the list adds indirection that every reader of the code has to follow.
What each pattern costs
| Pattern | What it gives you | What it costs |
|---|---|---|
| Composition (`children`) | Layout freedom with almost no API | No shared state between the parts |
| Lifting state | Simple, explicit data flow | Prop drilling and re-rendering of the parent's whole subtree as the tree grows |
| Render props | Consumer controls output, logic is reused | Nested function children, harder to read, extra closures on every render |
| HOCs | Cross-cutting behavior applied to many components | Prop name collisions, wrapper layers in the tree, lost static properties, hard to type |
| Custom hooks | Logic reuse without extra tree layers | Reuses logic only, not markup, structure, or accessibility |
| Compound components | Expressive JSX, consumer-chosen layout and order | Requires context, can be misused outside the parent, children must stay in the tree |
| Control props | Parent can own the state when it needs to | Two code paths (controlled and uncontrolled) to test |
| State reducer | Consumers can change state transitions | Your action types become public API |
| Prop getters | Correct handler and ARIA merging | Consumers must learn to call the getters |
| Headless hooks and components | Maximum styling freedom | The consumer must build all markup and styling |
Decision flow
Choosing between close alternatives
Render props, HOCs, or hooks
For new code that shares stateful logic, a custom hook is almost always the first choice. It adds no wrapper to the tree, composes with other hooks, and reads like ordinary code.
Render props still fit when the component must control something a hook cannot, such as where a child is rendered or when a list item function is called. A virtualized list that calls renderRow(index) is a good example.
HOCs fit when you must wrap components you do not own, or apply the same behavior across many components at one boundary, such as an error boundary or an auth gate. Their costs are listed in the table, so do not choose them for logic that a hook can share.
Compound component or configuration props
A single component with a prop like items={[{ label, content }]} is fine when the structure is fixed and the options are few. Switch to a compound component when consumers keep asking for variations, such as an icon in one tab, a disabled tab, or an extra element between the tab list and the panels. If each request adds a prop, the component wants to be compound.
Compound component or hook
A compound component ships markup, structure, and accessibility. A headless hook ships only behavior. Choose the compound component when most consumers want the same look and roles. Choose the hook, with prop getters, when design systems differ so much that your markup would get in the way.
Failure modes to check for
Unstable context values
A provider that passes a new object every render re-renders every consumer, even when nothing changed. Memoize the value.
import { createContext, useContext, useMemo, useState } from 'react';
const AccordionContext = createContext(null);
function useAccordion() {
const ctx = useContext(AccordionContext);
if (!ctx) {
throw new Error('Accordion subcomponents must be rendered inside <Accordion>');
}
return ctx;
}
export function Accordion({ children }) {
const [openId, setOpenId] = useState(null);
const value = useMemo(() => ({ openId, setOpenId }), [openId]);
return (
<AccordionContext.Provider value={value}>
{children}
</AccordionContext.Provider>
);
}
function Item({ id, title, children }) {
const { openId, setOpenId } = useAccordion();
const open = openId === id;
return (
<section>
<button aria-expanded={open} onClick={() => setOpenId(open ? null : id)}>
{title}
</button>
{open ? <div role="region">{children}</div> : null}
</section>
);
}
Accordion.Item = Item;setOpenId from useState is stable, so openId is the only dependency. The guard in useAccordion also turns a confusing Cannot destructure property of null error into a clear message.
Hidden coupling
Compound components work through context, so they can only coordinate inside the provider. If a consumer wraps Tabs.Tab in a component of their own, that still works, because context passes through any depth. If they use React.Children.map to inspect or clone children, a wrapper breaks it. Prefer context over cloning children for that reason.
Two modes drifting apart
A component that supports controlled and uncontrolled use has two code paths. A common bug is switching between them during the component's life, when a parent passes undefined and later a value. Decide the mode once, document that it must not change, and test both paths.
Public API you did not mean to publish
A state reducer exposes your action types. Renaming 'toggle' to 'flip' then breaks consumers. Add a reducer prop only when a consumer has a real need, and export the reducer and its action types so they are explicit.
A worked decision
You are building a dropdown menu for an internal design system used by three teams.
- Plain props with an
optionsarray cover the first release. Stop here if that is all anyone asks for. - Teams then ask for dividers, icons, and disabled items. Switch to a compound component:
Menu,Menu.Trigger,Menu.Item,Menu.Divider. Context carries the open state. - One team needs the menu open while a tutorial runs. Add control props:
openandonOpenChange. - Another team wants the menu to stay open after an item is picked. A reducer prop could allow it, but a simpler
closeOnSelectprop covers it. Use the prop until a second, different override request arrives. - A fourth team has its own component library and needs only behavior. Extract the logic into a
useMenuhook with prop getters, and rebuildMenuon top of it.
Each step answers a request that has already happened. None of them is built in advance.
Exercise
A SearchBox component needs the same debounced-input logic as a FilterBar and a CommandPalette. Each has different markup. Which pattern fits, and why not a HOC?
Show answer
A custom hook, such as useDebouncedValue. It shares the logic without adding wrapper components, and each component keeps its own markup. A HOC would add a wrapper layer, could collide on prop names, and would not help with the differing markup.
Exercise
Your Tabs provider passes value={{ value, setValue }} without useMemo. The parent of Tabs re-renders for an unrelated reason. What happens to the tabs and panels, and how do you fix it?
Show answer
The provider creates a new object on each render, so every Tab and Panel that reads the context re-renders even though value has not changed. Wrap the object in useMemo(() => ({ value, setValue }), [value]). The setValue function from useState is stable, so it does not need to be a dependency.