Paweł Piech

Composing components with context

A shared component starts small. A dialog takes a title and some children. Then one page needs a footer. Another needs a custom header. A third wants the close button on the left, or no close button at all. Each request adds a prop, and after a few months the component has a dozen flags that no one can explain.

I hit this often with tables, dialogs, and page layouts. The fix for me was not a better prop list. It was to stop steering every part of the component through props and let the page compose the parts it needs.

The prop problem

Here is a dialog after a year of small requests:

<Dialog
  title="Delete project"
  description="This cannot be undone."
  showClose
  showFooter
  footerAlign="end"
  confirmLabel="Delete"
  onConfirm={remove}
  cancelLabel="Cancel"
  showIcon
  icon="warning"
  bodyPadding="compact"
>
  ...
</Dialog>

Every page pays for the needs of every other page. The types grow, the branches inside the component grow, and a change for one page can break another. Reading the call site does not tell me what the dialog will look like. I have to open the component and follow the flags.

Split the component into parts

The first change is to expose the parts and let the page put them together:

<Dialog>
  <Dialog.Header>
    <Dialog.Icon variant="warning" />
    <Dialog.Title>Delete project</Dialog.Title>
  </Dialog.Header>
  <Dialog.Body>This cannot be undone.</Dialog.Body>
  <Dialog.Footer>
    <Button onClick={close}>Cancel</Button>
    <Button onClick={remove}>Delete</Button>
  </Dialog.Footer>
</Dialog>

The call site now shows the result. A page that needs no footer does not render one. A page with a different header writes a different header. No new props are needed for either case, and the dialog does not branch on flags.

The parts still share behavior. The footer must close the dialog when a button is pressed. The body needs to know if it is scrollable. The header needs the close handler. That shared state is what context is for.

Share the wiring with context

The dialog owns a small state and passes it down with context:

type DialogContextValue = {
  close: () => void;
  titleId: string;
};

const DialogContext = createContext<DialogContextValue | null>(null);

function useDialog() {
  const value = useContext(DialogContext);
  if (value === null) {
    throw new Error("Dialog parts must be used inside Dialog");
  }
  return value;
}

The null check is not noise. It makes the context safe to use. A part rendered outside the dialog fails at once with a clear message, instead of reading undefined later. When a part calls close, it gets the same function the dialog uses. The page does not pass it down by hand.

Type safety comes from the data, not the props

Composition does not remove types. It moves them to the data each part owns. A dialog that fetches something has states, and the parts for each state are different. I model the state as a union, give the variants a short readable name, and let the page choose the part:

<Dialog>
  <Dialog.Body>
    {isLoading && <Spinner label="Loading project" />}
    {isError && <ErrorBox error={state.error} />}
    {isSuccess && <ProjectForm project={state.data} />}
  </Dialog.Body>
</Dialog>;

The names read like plain English, and each one is still a check of the same state. They are aliases, not separate flags, so the union stays the source of truth. TypeScript follows the alias too. Inside the error branch it knows the state is the error variant, so state.error exists. The loading branch cannot read project data. The success branch always has a project. There is no optional field and no fallback. The page decides which part fits each state, so two pages can show the same dialog with different bodies and both stay correct.

This is the part that surprised me. The old dialog tried to handle every state inside one component, so its props had to be optional and wide. The composed dialog has narrow parts. Each part takes exactly the data it renders, and the page connects them.

What changes become easy

When a page needs a new look, it writes a new part or rearranges the existing ones. The shared component does not change, so other pages do not move. A new state adds one branch in the page that has it. A page without that state never sees the branch.

Reviewing a change is easier too. The diff is at the call site, where the layout lives, not buried in a switch inside the shared component. I can read the change and see the screen it produces.

When not to use it

Composition is not free. It adds files and names. For a button or a badge, a few props are clearer than four parts. I reach for composition when the component has regions that pages want to change in different ways: headers, footers, toolbars, empty states, and state-specific bodies. If every page uses the component the same way, keep the simple prop API.

The rule I use is this: if I am adding a prop whose only job is to hide or replace a region, I stop and make that region a part. Props describe values. Composition describes structure. Context shares the wiring that the structure needs. Together they keep a shared component small, typed, and open to change.