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.
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, notisDisabled.onChange, notonValueUpdate. 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
showHeaderorhideIcondoubles 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:
// 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.
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.
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.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:
<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:
<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:
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.
What does the mergeProps example print?
const props = mergeProps(fromTrigger, fromChild); console.log(props.type, "|", props.className, "|", props["aria-expanded"]); props.onClick();
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:
refis just a prop in React 19.ComponentProps<"button">includes it, so the spread forwards it with noforwardRef. Callers can focus your button or measure it, and libraries likeasChildcan attach their ref.- Spread order is a decision.
<button type="button" {...rest}>lets callers overridetype.<button {...rest} type="button">locks it. Lock only what would break the component. - Merge, do not replace,
classNameand handlers. If your component sets classes and the caller passesclassName, combine them with a class-merging helper such ascn()(Tailwind design systems coveredclsxplustailwind-merge) so the caller'spx-6beats yourpx-4. If you need your ownonKeyDown, call the caller's too.
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:
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.
Tokens are the only place raw values live. Everything above refers to them by name.
Match each request to the API pattern that fits best.
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.
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:
v4.2
Add the replacement
Ship `open` / `defaultOpen` / `onOpenChange` next to the old `isOpen`. Both work. Docs show only the new API.
v4.2
Warn in development
Log a deprecation warning once per prop in development builds, naming the replacement and linking to the migration guide.
v4.3
Ship a codemod
A script that rewrites `isOpen` to `open` across a repo, for example with jscodeshift or ast-grep.
v4.x
Track usage
Search the monorepo or ask teams to run the codemod. Help the biggest consumers migrate.
v5.0
Remove it
Delete the old prop in a major release, with the change in the changelog and the codemod linked again.
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 the steps for safely replacing a prop in order.
- Tap the steps below in the right order.
Button should be released as a major version?- controlled component
- A component whose state is owned by the parent through a
valueprop and reported withonChange. 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
startIconorchildren, 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
asprop. Flexible but hard to type well. - variant
- A named, closed set of style options such as
sizeortone, mapped to design tokens. - codemod
- A script that rewrites source code automatically, shipped with a breaking release to migrate callers.