Building a Design System and Component Library

A design system is a product for other engineers and designers. This guide shows how to build its parts, keep it correct as it changes, and get many teams to use it.

Frontend system design · Pattern

Be able to design tokens, themes, and component APIs for a shared library. Be able to explain how it is tested, versioned, documented, and adopted across a large company.

Correctness contract: Every component meets WCAG 2.2 AA in every theme. A minor or patch release never breaks a consumer's build or behavior. One token change updates every product that uses it, with no hand edits.

You know HTML, CSS, JavaScript, and React or a similar component framework. Tokens, headless components, and visual regression testing are explained below. Numbers are teaching estimates.

Picture a company with 30 product teams and 12 web apps. Each team built its own button. There are now 14 shades of blue, 9 date pickers, and 5 modals, and 3 of those modals trap keyboard users forever. A rebrand would take a year. A design system fixes this by giving everyone one source for colors, spacing, and type, and one set of tested components. But a design system can also fail. If it is hard to use, slow, or breaks apps on upgrade, teams fork it or ignore it. This guide covers both sides: how to build the pieces, and how to run it as a product that teams choose to use.

Contents

  1. Concepts to understand first
  2. 1. What the system must provide
  3. 2. Scope and budgets
  4. 3. Design tokens and their tiers
  5. 4. Theming and dark mode
  6. 5. Component API design
  7. 6. Headless vs styled components
  8. 7. Accessibility baked in
  9. 8. Versioning and deprecation
  10. 9. Documentation and visual regression testing
  11. 10. Adoption across teams
  12. 11. Bundle size and CSS strategy
  13. 12. Failure modes
  14. 13. Trade-offs
  15. 14. Interview angle
  16. 15. Summary
  17. 16. Common mistakes
  18. Worked example: renaming a Button prop across 12 apps
  19. Code lab: resolve tokens into themed CSS
  20. Check yourself
  21. Key terms
  22. Further reading

Concepts to understand first

Design token

A token is a named design decision stored as data. It has a name and a value, such as color.text.primary = #111827. Code and design tools read tokens instead of raw values.

Example. A rebrand changes blue.600 from #2563eb to #1d4ed8 in one file. The build updates CSS, iOS, and Android outputs, and every product picks it up on the next release.

Limit. Tokens help only if products use them. A raw hex color in product code bypasses the system. Lint rules must catch that.

Token tiers

Tokens come in layers. Primitive tokens are the raw palette. Semantic tokens say what a value is for. Component tokens say where it is used. Each layer points to the one below it.

Example. button.bg points to color.accent, which points to blue.600 in light mode and blue.300 in dark mode.

Limit. Too many tiers make it hard to trace a value. Three tiers is usually enough. Component tokens are optional for simple components.

Headless component

A headless component gives behavior and accessibility, but no styles. It handles keyboard, focus, and ARIA. You add the look.

Example. A headless Menu handles arrow keys, typeahead, role="menu", and closing on Escape. The styled layer adds colors and spacing from tokens.

Limit. Teams that use only the headless layer can make inaccessible visual choices, such as low contrast. Behavior is safe, looks are not.

Semantic versioning

A version has three numbers: major, minor, and patch. A patch fixes bugs. A minor adds features. A major may break consumers. Consumers use ranges such as ^4.2.0 to accept safe updates.

Example. Adding a size="xs" option is minor, so 4.2.0 becomes 4.3.0. Removing the danger prop is major, so it waits for 5.0.0.

Limit. "Breaking" is wider than API shape. A changed DOM structure, a new focus behavior, or a 2 pixel layout shift can break someone's tests.

Visual regression testing

A test renders each component state in a real browser, takes a screenshot, and compares it to an approved baseline image. Any pixel change beyond a threshold fails the test until a human approves it.

Example. A padding change in Input also shifts DatePicker, which uses it. The screenshot diff shows both, so nobody ships a surprise.

Limit. Fonts, animations, and GPU differences cause flaky diffs. Run in a fixed container, turn off animations, and load fonts before the screenshot.

1. What the system must provide

Treat the design system like a product. Its users are engineers and designers. Write down what they need before you build.

Functional requirements

Non-functional requirements

Intuition

A design system competes with "I will just build it myself". Every rule you add is a cost to your users. It must give back more than it takes, in speed, quality, or safety.

2. Scope and budgets

Scale

Size budgets

Testing scale

Count screenshots before choosing a tool. 60 components times about 8 stories each is 480 stories. Times 2 themes and 2 viewports is 1,920 screenshots. At about 0.5 seconds each on 8 parallel browsers, a full run takes about 2 minutes. That is fine per pull request. Adding 3 brand themes would push it to almost 5,000 screenshots, so test brands only on the components they change.

Upgrade cost

If a major release forces each of 12 apps to spend 3 engineer-days, that is 36 days of company time. A codemod that cuts this to half a day per app saves about 30 days. So codemods pay for themselves after one major release.

3. Design tokens and their tiers

Token pipeline diagram: design tool variables sync into token source files in git. A CI build resolves aliases, checks contrast, and emits CSS custom properties, TypeScript constants, and native files. The component library uses the CSS variables and typed names, publishes to the registry, and product apps install it and set the theme at runtime.
Figure 1. Tokens live in git as data. One build creates every platform's output, so web, iOS, and Android always agree.

The three tiers

Why tiers? Dark mode changes what color.bg.surface points to, but not what button.primary.bg means. A rebrand changes the primitives. Each kind of change touches one layer.

Naming

Format and build

Store tokens as JSON. The W3C Design Tokens Community Group format uses $value and $type fields and {alias} references. A build tool such as Style Dictionary reads the files and writes:

The build also checks rules. It fails on alias cycles, unknown references, and text and background pairs that miss WCAG contrast.

Syncing with design tools

Design tools now have variables that map well to tokens. Pick one source of truth. A common choice is git as truth, with a plugin that opens a pull request when designers change variables. Code review then covers design changes too, and the history is in one place.

Tip

Emit semantic tokens as CSS variables, and have component styles use them with var(). Then a theme switch is one attribute change on <html>. No component re-renders, and no JavaScript runs per component.

4. Theming and dark mode

How a theme switch works

:root {
  color-scheme: light;
  --color-bg-surface: #ffffff;
  --color-text-primary: #111827;
  --color-accent: #2563eb;
}
[data-theme="dark"] {
  color-scheme: dark;
  --color-bg-surface: #111827;
  --color-text-primary: #f9fafb;
  --color-accent: #93c5fd;
}
.ds-button-primary {
  background: var(--color-accent);
  color: var(--color-bg-surface);
}

Setting data-theme="dark" on <html> swaps every variable at once. The browser recomputes styles in one pass. This costs a few milliseconds even on large pages. The color-scheme property tells the browser to draw scrollbars and native form controls in the matching style.

Following the system setting

No flash of the wrong theme

If React sets the theme after hydration, dark mode users see a white flash on every load. Fix it before first paint. Put a tiny inline script in the document head. It reads the saved choice from localStorage or a cookie, and sets data-theme on <html>. With server rendering, read a cookie on the server and send the right attribute in the HTML.

Dark mode is not inverted light mode

Brand themes and scoped themes

A sub-product may need its own accent. Add a brand theme that overrides only a few semantic tokens. Because themes are attribute selectors, they can nest. A marketing banner can set data-theme="dark" on one section of a light page.

Mistake

Storing theme colors in a JavaScript context and passing them as inline styles. Every theme change re-renders the whole tree, server rendering cannot know the theme, and styles cannot be cached. Use CSS variables and let the browser do the work.

5. Component API design

A component API is a contract that hundreds of call sites depend on. It is very hard to change later. Design it with care.

Consistent prop vocabulary

Controlled and uncontrolled

Support both. value plus onChange makes the parent the owner. defaultValue lets the component own state. The same pattern applies to open state: open, defaultOpen, and onOpenChange. Warn in development if a component switches between the two modes.

Composition over configuration

A Tabs component with props like tabs={[{label, content, icon, badge, disabled}]} grows a new prop for every request. Compound components scale better:

<Tabs defaultValue="billing">
  <Tabs.List aria-label="Account settings">
    <Tabs.Trigger value="profile">Profile</Tabs.Trigger>
    <Tabs.Trigger value="billing">Billing <Badge>2</Badge></Tabs.Trigger>
  </Tabs.List>
  <Tabs.Panel value="profile">...</Tabs.Panel>
  <Tabs.Panel value="billing">...</Tabs.Panel>
</Tabs>

The parent shares state through context. Each part handles its own ARIA: triggers get role="tab" and aria-selected, panels get role="tabpanel" and aria-labelledby. Consumers can put anything inside a trigger, and the library never needs a badge prop.

Escape hatches

Types as documentation

Use TypeScript to block wrong use. An IconButton can require aria-label in its type, so an unlabeled icon button does not compile. Discriminated unions can say "href is allowed only when as="a"".

Interview

When asked to design a component, start from the call site. Write the JSX a product engineer would type. Then derive the props. Interviewers look for controlled and uncontrolled support, composition, ref forwarding, and ARIA handled inside.

6. Headless vs styled components

Two layers

Why split them

Build or buy the behavior layer

Building your own gives full control, but costs a lot of specialist time and screen reader testing. Wrapping a mature open-source headless library gives years of bug fixes for free. The risk is dependency on its roadmap. A common choice is to wrap one, and keep your public API your own, so you can swap the inside later.

Which layer do teams import?

Most teams should import only the styled layer. Expose the headless layer as an advanced entry point, such as @acme/ds/primitives. Document that its users own visual accessibility, such as contrast and focus rings.

7. Accessibility baked in

The biggest value of a design system is that accessibility is solved once. If Dialog is correct, 400 engineers get correct dialogs without studying focus traps.

Follow the ARIA Authoring Practices

The WAI-ARIA Authoring Practices Guide (APG) describes the expected keyboard and ARIA behavior for each widget. Implement those patterns exactly. Users of screen readers expect a menu to behave like every other menu.

What each component must handle

Testing accessibility

Mistake

Adding ARIA to fix a div that should be a button. <div role="button"> still needs tabindex, Enter and Space handling, and disabled logic. A native <button> gives all of that for free.

8. Versioning and deprecation

Package layout

What counts as breaking

Release flow

Each pull request adds a changeset file that says "patch", "minor", or "major" and a sentence for the changelog. The release job reads these, bumps versions, writes the changelog, and publishes. Reviewers check the level, because a wrong "minor" breaks 12 apps.

Deprecation, step by step

  1. Add the new API next to the old one in a minor release.
  2. Mark the old one with a JSDoc @deprecated tag. Editors show it with a strike-through.
  3. Log a development-only warning once per page: "Button danger is deprecated. Use tone="critical". Run the codemod ds-codemod button-tone."
  4. Ship a codemod that rewrites call sites automatically, using a tool such as jscodeshift.
  5. Measure remaining usage by scanning all repos. Help the last few teams directly.
  6. Remove the old API in the next major, at least one quarter later.

Support window

Support the current major and the previous one for security and critical bug fixes, for example for 6 months. Longer windows split your team's time across branches.

9. Documentation and visual regression testing

Release pipeline diagram: a pull request with a changeset renders Storybook stories. Unit tests, accessibility checks, and visual regression screenshots run against them. Screenshots are diffed against stored baselines and a human approves changes. On merge a release job bumps versions and publishes to npm. A dependency bot opens upgrade pull requests with codemods in product apps.
Figure 2. Stories are the single list of states. Docs, tests, and screenshots all read from them.

Stories as the source of states

Write one story for each meaningful state: default, hover, focus, disabled, loading, error, long text, right-to-left, and each size. Tools like Storybook render stories in isolation. The same stories feed the docs site, the interaction tests, the axe scan, and the screenshot tests. One list, four uses.

What good docs contain

Visual regression in practice

Tip

Track the flake rate. If more than about 1 in 50 runs shows false diffs, people start approving without looking. Then the tests give false safety. Fix flakes as seriously as real bugs.

10. Adoption across teams

A perfect library that nobody uses has no value. Adoption is a product and people problem as much as a technical one.

Operating model

Make the right thing easy

Measure adoption

Migrating an old app

Do not ask a team to rewrite their app. Start with tokens: map their colors to semantic tokens so theming works. Then replace the most-used components one at a time, often Button, Input, and Dialog first. Each step ships alone and gives value alone.

Intuition

Teams adopt a system when it saves them time this week. They resist it when it only promises consistency next year. Lead with things that save time: dark mode for free, accessible dialogs, and faster builds.

11. Bundle size and CSS strategy

Tree shaking

How styles are delivered

For a shared library, static CSS plus CSS variables is the safest choice. It works with any framework, any rendering mode, and any bundler.

Specificity and isolation

Library styles should be easy to override, not fight product styles. Put library styles in a CSS cascade layer, such as @layer ds. Unlayered product styles then win without !important. Prefix class names, such as ds-, to avoid clashes with old global CSS.

Enforce budgets

Run a size check per entry point in CI, with tools such as size-limit. Report the change in every pull request. Keep a dashboard of the gzipped size of each component over time.

12. Failure modes

13. Trade-offs

Strict system vs flexible system

Build the behavior layer vs wrap a library

Monolithic package vs many packages

Runtime CSS-in-JS vs static CSS

14. Interview angle

A common prompt is "Design a component library for a company with 50 teams" or "Design a Select component". Strong answers cover:

  1. Users and goals first. Who uses it, how many apps, which frameworks, which platforms.
  2. Tokens and tiers. Primitive, semantic, and component. CSS variables for runtime theming.
  3. API from the call site. Controlled and uncontrolled, composition, refs, escape hatches, typed props.
  4. Accessibility inside. APG patterns, focus management, tests with axe plus manual screen readers.
  5. Change management. Semver, changesets, deprecation steps, codemods, support window.
  6. Quality gates. Stories, interaction tests, visual regression, size budgets.
  7. Adoption. Operating model, lint rules, metrics, migration path for old apps.
Interview

A staff-level signal is talking about the organization, not only code. Mention who approves breaking changes, how you measure adoption, and how you stop forks. Then tie it back to numbers, such as upgrade cost across 12 apps.

15. Summary

16. Common mistakes

Worked example: renaming a Button prop across 12 apps

Designers decide that variant="danger" should become tone="critical", because "danger" mixes look and meaning. The library is at 4.6.0. Here is how the change rolls out without breaking anyone.

  1. An RFC explains the change and the plan. The design system council approves it. The target is removal in 5.0.0, one quarter later.
  2. In 4.7.0 (minor), Button accepts tone. The old variant="danger" still works and maps to tone="critical" inside. Screenshots show no pixel change for both forms.
  3. The TypeScript type marks "danger" with @deprecated. Editors show it struck through.
  4. In development builds, Button logs one warning per page that names the codemod. Production builds strip the warning.
  5. The team ships a jscodeshift codemod. It rewrites variant="danger" to tone="critical", and flags dynamic values such as variant={v} for a human.
  6. A usage scan across all repos finds 412 call sites in 12 apps. The dependency bot opens upgrade pull requests that bump to 4.7.0 and run the codemod. 9 apps merge within two weeks.
  7. The scan shows 37 sites left in 3 apps, mostly dynamic values. A core engineer pairs with those teams for an afternoon each.
  8. The scan reaches zero. 5.0.0 removes "danger" from the type and the runtime mapping. The changelog links the codemod for any late upgraders.
  9. The 4.x line gets security fixes for 6 more months, then it is closed.
  10. Total cost: about 2 engineer-weeks for the core team and less than 1 hour per product team. A hand migration would have cost about 36 engineer-days.

Code lab: resolve tokens into themed CSS

This script models a tiny token build. It resolves {alias} references through three tiers, emits a CSS block per theme, and fails clearly on alias cycles and unknown tokens. Save it as tokens.mjs and run node tokens.mjs with Node 18 or later.

const primitives = {
  "blue.600": "#2563eb", "blue.300": "#93c5fd",
  "gray.900": "#111827", "gray.50": "#f9fafb", "space.2": "8px",
};
const themes = {
  light: { "color.bg": "{gray.50}", "color.text": "{gray.900}", "color.accent": "{blue.600}" },
  dark:  { "color.bg": "{gray.900}", "color.text": "{gray.50}", "color.accent": "{blue.300}" },
};
const components = { // component tokens point at semantic tokens, never at raw values
  "button.bg": "{color.accent}", "button.text": "{color.bg}", "button.padding": "{space.2}",
};

function resolve(name, table, seen = []) {
  if (seen.includes(name)) throw new Error(`Alias cycle: ${[...seen, name].join(" -> ")}`);
  const raw = table[name];
  if (raw === undefined) throw new Error(`Unknown token: ${name} (from ${seen.at(-1) ?? "root"})`);
  const m = /^\{(.+)\}$/.exec(raw);
  return m ? resolve(m[1], table, [...seen, name]) : raw;
}

function buildCss(themeName) {
  const table = { ...primitives, ...themes[themeName], ...components };
  const lines = Object.keys({ ...themes[themeName], ...components }).map(
    (name) => `  --${name.replace(/\./g, "-")}: ${resolve(name, table)};`,
  );
  const selector = themeName === "light" ? ":root" : `[data-theme="${themeName}"]`;
  return `${selector} {\n${lines.join("\n")}\n}`;
}

console.log(buildCss("light"));
console.log(buildCss("dark"));
try {
  resolve("a", { a: "{b}", b: "{c}", c: "{a}" });
} catch (e) { console.log(e.message); }
try {
  resolve("button.border", { ...components, "button.border": "{color.border}" });
} catch (e) { console.log(e.message); }

Expected output: a :root block where --button-bg is #2563eb, and a dark block where it is #93c5fd. Then two errors: Alias cycle: a -> b -> c -> a and Unknown token: color.border (from button.border). As an exercise, change the build so component tokens emit var(--color-accent) instead of the final hex value. Then the dark block no longer needs to repeat component tokens at all.

Check yourself

  1. Why should product code use color.text.danger and not red.600?
    Answer

    The semantic token names a purpose, so each theme can point it at a different primitive. Dark mode can use a lighter red, and a rebrand can change the palette, with no product code changes. A primitive used directly stays the same in every theme.

  2. How do you avoid a white flash for dark mode users on page load?
    Answer

    Set data-theme before first paint. With server rendering, read a cookie and put the attribute in the HTML. Otherwise use a tiny inline head script that reads the saved choice. Do not wait for React hydration.

  3. Why are compound components often better than a big config prop for Tabs?
    Answer

    Consumers can put any content in each part, so the library does not need a new prop for every request such as icons or badges. Each part still handles its own ARIA and keyboard behavior through shared context.

  4. A team changes the default of Dialog to close on outside click. Is that a minor release?
    Answer

    No. It changes default behavior that consumers rely on, for example forms in dialogs could lose data. It is a breaking change. Ship it behind an opt-in prop in a minor release, and change the default only in a major.

  5. Why should the library declare React as a peer dependency?
    Answer

    So the app supplies one copy of React. If the library bundled its own, hooks and context would break, because components would run against two different React instances.

  6. Your visual tests fail randomly on 1 run in 10. What do you check first?
    Answer

    The environment: run in one fixed Docker image, wait for document.fonts.ready, turn off animations and transitions, and freeze time and random data. Flaky tests train people to approve diffs without looking.

Key terms

Design token
A named design decision stored as data, such as a color or a spacing value.
Primitive token
A token that names a raw value in the palette or scale.
Semantic token
A token that names a purpose and points to a primitive. Themes change these.
CSS custom property
A CSS variable such as --color-accent, read with var() and changed at runtime.
color-scheme
A CSS property that tells the browser which color schemes a page supports, for native controls and scrollbars.
Headless component
A component that provides behavior and accessibility with no styles.
Compound component
A component made of parts, such as Tabs.List and Tabs.Panel, that share state through context.
Controlled component
A component whose value is owned by the parent through value and onChange.
Changeset
A small file in a pull request that states the version bump level and the changelog text.
Codemod
A script that rewrites source code automatically, used to migrate call sites.
Visual regression test
A test that compares screenshots of components with approved baseline images.
Cascade layer
A CSS @layer that sets the priority of a group of styles, independent of selector specificity.

Further reading

Primary references