Skip to content

Lesson 34 of 37React at scale

Designing Component APIs and Design Systems

Design props that age well: controlled and uncontrolled state, slots, asChild and render props, native prop spreading, variants, Storybook and deprecations.

20 min read0/5 questions

Your team owns the shared Select that forty product teams use. Version one took value and onChange. Then someone needed a default value, someone else needed an icon on the left, then on the right, then a custom option renderer, then a way to open it from outside. Two years later it has 31 props, three of them booleans that conflict, and every change breaks somebody's page. The component's code was never the hard part. Its API was, because once other people's code depends on a prop, that prop is a promise. This lesson is about making promises you can keep: patterns for props, state and composition that hold up when many teams build on your components.

Start from the call site

Before you write the component, write three or four places that will use it. API design is about the caller's code, not yours. A few principles hold almost everywhere:

  • Match the platform. If it acts like a native element, use native names: disabled, not isDisabled. onChange, not onValueUpdate. People already know the native names, and you can spread native props straight through.
  • Make the common case short. <Button>Save</Button> should just work. Defaults should be the choice most callers want.
  • Make invalid states impossible. If a toast has either an action button or a close button but never both, encode that in the type instead of documenting it.
  • Prefer composition to configuration. Every boolean like showHeader or hideIcon doubles the number of states you must test. Ten booleans is 1,024 combinations, and nobody tests those.

Here is configuration gone wrong next to composition:

Two ways to build a card
// Configuration: every layout is a prop, and every new need is another one
<Card
  showHeader
  headerTitle="Billing"
  headerIcon={<CreditCard />}
  showFooter
  footerPrimaryAction={{ label: "Save", onClick: save }}
/>
 
// Composition: the card owns layout and styling, the caller owns content
<Card>
  <Card.Header icon={<CreditCard />}>Billing</Card.Header>
  <Card.Body>...</Card.Body>
  <Card.Footer>
    <Button onClick={save}>Save</Button>
  </Card.Footer>
</Card>

The composed version never needs a footerSecondaryAction prop. When a team wants two buttons, they render two buttons.

For the either-or case, a discriminated union in the props makes the wrong combination a type error. React with TypeScript covered unions for state. The same trick works for props:

type ToastProps = { message: string } & (
  | { action: { label: string; onClick: () => void }; onClose?: never }
  | { onClose: () => void; action?: never }
);

Controlled and uncontrolled, both at once

Native inputs support two modes. <input defaultValue="a"> is uncontrolled: the input keeps its own state, and you read it when you need it. <input value={v} onChange={...}> is controlled: the parent owns the state, and the input shows whatever it is told. Good components support both, with the same naming triple: value, defaultValue, onChange (or checked, defaultChecked, onCheckedChange; open, defaultOpen, onOpenChange).

Why both? Most callers do not care about the state and want <Accordion defaultValue="faq-1">. Some need to drive it from outside: open a panel from a URL, reset a form, sync two widgets. If you only support controlled, everyone writes boilerplate state. If you only support uncontrolled, the second group starts asking for ref.current.open() methods.

The standard implementation is a small hook. Design system libraries all have their own version, often called useControllableState.

ReactControllableSwitch.tsx
import { useEffect, useRef, useState } from "react"; function useControllableState<T>({ value, defaultValue, onChange }: { value?: T; defaultValue: T; onChange?: (next: T) => void;}) { const isControlled = value !== undefined; const [internal, setInternal] = useState(defaultValue); const wasControlled = useRef(isControlled); useEffect(() => { if (wasControlled.current !== isControlled) { console.warn("A component switched between controlled and uncontrolled. Decide on the first render."); } }, [isControlled]); const current = isControlled ? value : internal; function setValue(next: T) { if (!isControlled) setInternal(next); onChange?.(next); } return [current, setValue] as const;} function Switch({ label, checked, defaultChecked = false, onCheckedChange }: { label: string; checked?: boolean; defaultChecked?: boolean; onCheckedChange?: (next: boolean) => void;}) { const [on, setOn] = useControllableState({ value: checked, defaultValue: defaultChecked, onChange: onCheckedChange }); return ( <button role="switch" aria-checked={on} onClick={() => setOn(!on)} style={{ display: "block", margin: "6px 0" }}> {label}: {on ? "On" : "Off"} </button> );} export default function App() { const [emails, setEmails] = useState(true); return ( <div> <Switch label="Uncontrolled" defaultChecked /> <Switch label="Controlled" checked={emails} onCheckedChange={setEmails} /> <button onClick={() => setEmails(false)}>Parent: turn controlled off</button> <Switch label="Controlled, no handler" checked={false} onCheckedChange={(next) => console.log("asked to become", next)} /> </div> );}

The uncontrolled switch keeps its own state. The controlled one follows the parent, so the parent's reset button works. The third one is controlled but the parent never updates checked, so it stays off however often you click it, and the console shows the requests being ignored. That is the most common bug report a design system team receives, and it is correct behavior: a controlled component shows what it is told.

Predict the outputJavaScript

A parent renders <Switch label="Beta" checked={undefined} /> on the first render, then <Switch label="Beta" checked={true} /> after data loads. Using the hook above, what happens?

// render 1: checked={undefined}  -> isControlled = false
// render 2: checked={true}       -> isControlled = true
// The effect compares wasControlled.current with isControlled.
Need a nudge? Hints walk you through it.

Three rules keep this pattern honest. Decide the mode on the first render. Call onChange in both modes, so an uncontrolled caller can still listen. And never copy the value prop into state with an effect. That creates two sources of truth that drift apart, the exact problem Lifting state up warned about.

Slots: passing UI, not settings

The cheapest composition tool is a prop that takes a React node. Instead of iconName="search" plus iconPosition="left", accept startIcon and endIcon as React.ReactNode. The component decides where they go and how they are spaced. The caller decides what they are. This is called a slot, and children is just the default one.

When several pieces need to share state, such as tabs and their panels, you move up to compound components with a shared context. React architecture covers how they work. The API point is that <Tabs.List> and <Tabs.Panel> let callers rearrange, wrap and style parts that a single <Tabs items={...}> prop would lock down.

Handing over the element: as, asChild and render

Sooner or later someone needs your Button styles on a link, or your Dialog.Trigger behavior on their own button. There are three common answers, and you will see all of them in real libraries.

A polymorphic as prop. <Button as="a" href="/pricing">. Easy to read, painful to type. Props must change with as (an a needs href, a button takes type), which needs generic types that slow the compiler and produce long error messages. Many libraries have moved away from it.

asChild, made popular by Radix. The component renders no element of its own. It merges its props, its ref and its event handlers onto its single child:

Radix style
<Dialog.Trigger asChild>
  <Button variant="ghost">Edit profile</Button>
</Dialog.Trigger>

A render prop, used by Base UI. You pass the element (or a function that receives the props) to render:

Base UI style
<Menu.Trigger render={<Button variant="ghost" />}>Options</Menu.Trigger>
<Menu.Trigger render={(props) => <button {...props} className="my-trigger" />}>Options</Menu.Trigger>

Both depend on prop merging, and the merge rules are where bugs live. Run this simplified version of what asChild does underneath:

TypeScriptmergeProps.ts
type Props = Record<string, unknown>;type Handler = (...args: unknown[]) => void; function mergeProps(slot: Props, child: Props): Props { const merged: Props = { ...slot, ...child }; for (const key of Object.keys(slot)) { const a = slot[key]; const b = child[key]; if (/^on[A-Z]/.test(key) && typeof a === "function" && typeof b === "function") { merged[key] = (...args: unknown[]) => { (b as Handler)(...args); (a as Handler)(...args); }; } else if (key === "className" && b) { merged[key] = `${a} ${b}`; } else if (key === "style" && b) { merged[key] = { ...(a as object), ...(b as object) }; } } return merged;} const fromTrigger = { type: "button", className: "trigger", "aria-expanded": false, onClick: () => console.log("trigger: toggle menu") };const fromChild = { type: "submit", className: "btn-ghost", onClick: () => console.log("child: track click") }; const props = mergeProps(fromTrigger, fromChild);console.log(props.type, "|", props.className, "|", props["aria-expanded"]);(props.onClick as Handler)();
Output
Press Run (⌘ Enter) to see what happens.

Child props win for plain values, class names are joined, styles are merged and both click handlers run. If your merge forgot the handler case, the child's onClick would silently replace the trigger's and the menu would never open.

Predict the outputJavaScript

What does the mergeProps example print?

const props = mergeProps(fromTrigger, fromChild);
console.log(props.type, "|", props.className, "|", props["aria-expanded"]);
props.onClick();
Need a nudge? Hints walk you through it.

Native props, refs and class names

For a component that wraps one native element, accept everything that element accepts. React with TypeScript showed React.ComponentProps<"button"> plus a rest spread. Three details decide whether the wrapper feels native:

  1. ref is just a prop in React 19. ComponentProps<"button"> includes it, so the spread forwards it with no forwardRef. Callers can focus your button or measure it, and libraries like asChild can attach their ref.
  2. Spread order is a decision. <button type="button" {...rest}> lets callers override type. <button {...rest} type="button"> locks it. Lock only what would break the component.
  3. Merge, do not replace, className and handlers. If your component sets classes and the caller passes className, combine them with a class-merging helper such as cn() (Tailwind design systems covered clsx plus tailwind-merge) so the caller's px-6 beats your px-4. If you need your own onKeyDown, call the caller's too.
components/ui/IconButton.tsx
type IconButtonProps = React.ComponentProps<"button"> & { label: string };
 
export function IconButton({ label, className, type = "button", onKeyDown, ...rest }: IconButtonProps) {
  return (
    <button
      type={type}
      aria-label={label}
      className={cn("inline-flex size-9 items-center justify-center", className)}
      onKeyDown={(e) => {
        onKeyDown?.(e);
        if (e.defaultPrevented) return;
        if (e.key === "Escape") e.currentTarget.blur();
      }}
      {...rest}
    />
  );
}

Making label required is an API choice that encodes accessibility: an icon-only button with no name is now a type error, not an audit finding.

Event props: name them for what happened

Native onChange hands you an event. For your own components, the more useful contract is usually the value: onValueChange(value), onOpenChange(open), onSelect(item). Callers should not have to dig through event.target to learn what your component already knows. If you also need the original event (to call preventDefault, for example), pass it as a second argument rather than instead of the value. Name callbacks after what happened, onDismiss, not what the caller should do, closeModal. The component does not know what the caller will do with it.

Shipping one library for React 18 and React 19

If your library must support both versions, a few React 19 changes matter. ref as a plain prop only works in 19, so libraries that still support 18 keep forwardRef, which keeps working in 19 (it is expected to be deprecated later). defaultProps on function components was removed in 19: use default parameter values in the destructuring, which work in both. propTypes checks are silently ignored in 19, so runtime prop validation must move to TypeScript or explicit checks. Declare react as a peer dependency with a range covering both versions, and run your test suite against each in CI. Once you drop 18, a codemod can remove the forwardRef wrappers.

Variants and tokens

Variant props are a closed set of names, not raw values. size="sm" and tone="danger", never padding={12} or color="#d33". Names map to design tokens, so a rebrand changes the tokens, not 4,000 call sites. Tailwind design systems covered tokens with @theme. On the component side, teams commonly use class-variance-authority (cva) or tailwind-variants to map variant names to classes:

components/ui/button-variants.ts
import { cva, type VariantProps } from "class-variance-authority";
 
export const buttonVariants = cva("inline-flex items-center gap-2 font-medium", {
  variants: {
    tone: { primary: "bg-primary text-primary-foreground", ghost: "bg-transparent", danger: "bg-destructive text-white" },
    size: { sm: "h-8 px-3 text-sm", md: "h-10 px-4" },
  },
  compoundVariants: [{ tone: "ghost", size: "sm", class: "px-2" }],
  defaultVariants: { tone: "primary", size: "md" },
});
 
export type ButtonVariantProps = VariantProps<typeof buttonVariants>;

VariantProps derives the prop types from the config, so the type and the styles cannot drift apart. Exporting buttonVariants also lets a link use button styles without any polymorphism at all.

Layers of a design system
  1. Design tokenscolor, spacing, radius, type scale
  2. Headless behaviorfocus, keyboard, ARIA (your own or a library)
  3. Styled primitivesButton, Input, Dialog, Select
  4. Product patternsConfirmDelete, SettingsForm, EmptyState

Tokens are the only place raw values live. Everything above refers to them by name.

1/4
Match the pairs0/5 matched

Match each request to the API pattern that fits best.

Choose an item, then its match on the other side.

Documenting and testing with Storybook

A design system lives or dies by its documentation. Storybook is the common tool: each component gets a file of stories, which are named examples of its states. Those stories become your docs, your manual test bench, and your automated tests.

Button.stories.tsx
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, fn, userEvent, within } from "storybook/test";
import { Button } from "./Button";
 
const meta = { component: Button, args: { children: "Save", onClick: fn() } } satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
 
export const Primary: Story = {};
export const Danger: Story = { args: { tone: "danger", children: "Delete" } };
 
export const ClickCallsHandler: Story = {
  play: async ({ args, canvasElement }) => {
    await userEvent.click(within(canvasElement).getByRole("button", { name: "Save" }));
    await expect(args.onClick).toHaveBeenCalledOnce();
  },
};

From the same stories, teams add an accessibility addon that runs axe on every story, interaction tests from play functions in CI, and visual regression testing, which screenshots each story and flags pixel changes for review. A story per state (loading, disabled, error, long text, right-to-left) is also the cheapest way to make reviewers look at the states nobody clicks by hand. Storybook's package names and test runner integration change between major versions, so follow the docs for your version.

Changing an API without breaking forty teams

A component library is a package with semver, and you need a clear definition of breaking. Removing or renaming a prop is obvious. Less obvious: changing a default, changing the rendered element or DOM structure (someone's CSS or test targets it), changing which element gets focus, or narrowing a type. Treat those as breaking too.

The playbook for removing something:

Retiring the isOpen prop
  1. v4.2

    Add the replacement

    Ship `open` / `defaultOpen` / `onOpenChange` next to the old `isOpen`. Both work. Docs show only the new API.

  2. v4.2

    Warn in development

    Log a deprecation warning once per prop in development builds, naming the replacement and linking to the migration guide.

  3. v4.3

    Ship a codemod

    A script that rewrites `isOpen` to `open` across a repo, for example with jscodeshift or ast-grep.

  4. v4.x

    Track usage

    Search the monorepo or ask teams to run the codemod. Help the biggest consumers migrate.

  5. v5.0

    Remove it

    Delete the old prop in a major release, with the change in the changelog and the codemod linked again.

Dialog.tsx (deprecation shim)
const warned = new Set<string>();
function deprecate(prop: string, replacement: string) {
  if (process.env.NODE_ENV !== "production" && !warned.has(prop)) {
    warned.add(prop);
    console.warn(`[ui] Dialog: \`${prop}\` is deprecated, use \`${replacement}\`. It will be removed in v5.`);
  }
}
 
export function Dialog({ isOpen, open = isOpen, ...rest }: DialogProps) {
  if (isOpen !== undefined) deprecate("isOpen", "open");
  // ...
}

Tools like Changesets make each pull request declare whether it is a patch, minor or major change, then generate the version bump and changelog. That forces the "is this breaking?" conversation at review time, when it is cheap.

Put it in order5 steps

Put the steps for safely replacing a prop in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Which change to a shared Button should be released as a major version?
Need a nudge? A hint rules out a wrong answer.
Key terms
controlled component
A component whose state is owned by the parent through a value prop and reported with onChange. It shows what it is told.
uncontrolled component
A component that keeps its own state, optionally seeded with defaultValue. The parent reads or listens instead of driving it.
slot
A prop that accepts a React node, such as startIcon or children, letting the caller supply UI the component places.
asChild
A pattern where a component renders no element of its own and merges its props, ref and handlers onto its single child.
polymorphic component
A component whose rendered element changes via an as prop. Flexible but hard to type well.
variant
A named, closed set of style options such as size or tone, mapped to design tokens.
codemod
A script that rewrites source code automatically, shipped with a breaking release to migrate callers.