Skip to content

    Frontend System Design

    Component Library Architecture

    Structure a shared React component library: a pure TypeScript core, thin components, one public entry point and package fields that limit what apps can import.

    By Published 12 min read

    • frontend-system-design
    • component-library
    • design-system
    • react
    Share

    Standard lessonadvancedReact labFrontend System Design

    Before this: Design Tokens and Theming, Component Composition and API Design

    What you'll learn: By the end of this lesson you will be able to split a shared React component library into a pure core, thin React components and one public entry point; keep design choices as data and keyboard rules in a testable reducer; say what the exports and sideEffects fields of package.json promise to consumers and what breaks when they are wrong; and test the public surface of a library like a contract.

    Think of a hardware shop that sells shelf brackets. Behind the counter is the stockroom: steel, drills, jigs. Customers never walk in there. They get a bracket in a box with a fixed set of fittings. The shop can change how brackets are made without anyone noticing, as long as the box and its fittings stay the same.

    A component library is the same arrangement. Apps receive a box (the public API) and the stockroom stays closed. When it is open, a team will reach in for a helper, and from that day the helper is part of your API whether you meant it or not.

    The running example is a storefront whose three apps (product page, checkout, account) share a Button and a Tabs. Component Composition and API Design covers one component's props; this lesson is about how the shared code is organised. Design tokens and theming are a separate lesson.

    The core idea

    Three statements carry the lesson.

    1. Put logic where it can be tested without a browser. React's docs say a reducer is "a pure function that doesn't depend on your component", so it can be exported and tested in isolation. A library that keeps its rules (which class names, which key moves focus) in pure functions and its React in thin wrappers gets fast, exact tests for the part that is easy to get wrong.
    2. A library has a public API and everything else is private. Semantic Versioning says software using it "MUST declare a public API". Without one, "breaking change" has no meaning.
    3. The package file is part of the architecture. The exports field decides which paths a consumer can import, and sideEffects tells bundlers which files they may drop. Both are promises, and a wrong one fails in production builds rather than in development.

    At the time of writing React is at 19.3, and the lab uses React 19.3.1, TypeScript 7.0.2 and Vitest 5.1.0.

    Three layers

    Illustration 1 (minimal): one function, one tabs reducer. The smallest useful unit is a function with no React in it. This one decides the class names of a button from named choices:

    export const buttonVariants = defineVariants({
      base: "btn",
      variants: {
        variant: { primary: "btn-primary", secondary: "btn-secondary", danger: "btn-danger" },
        size: { sm: "btn-sm", md: "btn-md", lg: "btn-lg" },
      },
      defaultVariants: { variant: "primary", size: "md" },
      compound: [{ when: { variant: "danger", size: "lg" }, classes: "btn-danger-lg" }],
    });

    buttonVariants({ variant: "danger", size: "lg" }) returns the string btn btn-danger btn-lg btn-danger-lg. It needs no DOM, no render and no mocks to test. The class names are made up for the lab.

    The second pure piece is a reducer for a tab list. It takes a state and an event and returns the next state, and an event that means nothing returns the same object:

    export function tabsReducer(state: TabsState, event: TabsEvent): TabsState {
      // "focus", "select" and "key" events; arrows wrap, Home and End jump,
      // Enter or Space select in manual mode. Unhandled: return `state` itself.
    }

    Figure 1. The three layers of the library and the one door

    Apps import only the public entry point. It exposes thin React components, which call a pure core.Storefront apps to Public entry (import); Public entry to React layer; React layer to Pure core (calls); Storefront apps to Internal files (blocked)LIBRARY PACKAGEStorefront apps: product, checkoutStorefrontappsproduct, checkoutPublic entry: index.ts, one doorPublic entryindex.ts, onedoorReact layer: thin componentsReact layerthin componentsPure core: variants, reducerPure corevariants, reducerInternal files: not exportedInternal filesnot exportedimportcallsblocked

    How to read this: the left side is the only thing apps are allowed to touch. The red path is a deep import into an internal file, which the package's exports field is there to refuse. The tested logic sits on the right, away from React.

    Layer Contains Depends on Tested with
    Pure core Variant resolution, state machines, attribute computation Nothing Plain asserts
    React layer Components that connect events and attributes to the core React, the core Testing Library under jsdom
    Public entry A list of re-exports The two layers above A surface test

    Design tokens and CSS sit beside these layers, so a theme change does not touch component code.

    Keep the React layer thin

    The lab's tabs component holds state, passes a key press to the reducer, spreads the attributes the core computed, and moves DOM focus. Focus is the one thing the reducer cannot do, because it is a side effect.

    function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
      const next = tabsReducer(state, { type: "key", key: event.key });
      if (next === state) return; // not handled: leave the browser's default alone
      event.preventDefault();
      setState(next);
      nodes.current.get(next.focused)?.focus();
    }

    Figure 2. One key press through the layers

    sequenceDiagram accTitle: A key press on a tab accDescr: The user presses the right arrow on a tab. The React component passes the key to the pure reducer. The reducer returns the next state. If it is a different object the component prevents the browser default, stores the state and moves DOM focus to the new tab. If it is the same object the component does nothing. participant U as User participant C as Tabs component participant R as tabsReducer participant D as DOM U->>C: keydown ArrowRight C->>R: state, key event R-->>C: next state alt next is a new object C->>D: preventDefault, then focus the new tab C->>C: setState(next) else same object C->>C: do nothing end

    How to read this: all decisions are made in the reducer. The component only reacts to its answer.

    Returning the same object for an unhandled key lets the component tell "handled" from "ignored" with one comparison, so it does not swallow keys such as Tab.

    What the tabs follow. The WAI-ARIA Authoring Practices tabs pattern gives each tab the role tab inside a tablist, aria-selected on the active tab, aria-controls pointing at its panel and aria-labelledby on the panel. Left and Right Arrow move focus and wrap; Home and End are optional; activating on focus is recommended only when panels appear without noticeable latency, otherwise Space or Enter activates. The lab implements both modes. It keeps one tab in the page's tab order and gives the others tabindex="-1", a roving tabindex in the keyboard-interface page's terms; the alternative, aria-activedescendant, keeps DOM focus on the container.

    The same site cautions that the examples need testing with assistive technology before production use. The lab's jsdom tests show that roles, attributes and focus change as intended, not what a screen reader says.

    Design choices as data

    The variants function turns the design system's named axes into code. Compare two ways to expose a danger button:

    • Boolean props (danger, large, outline) allow combinations nobody designed.
    • Named axes (variant, size) hold one value each, and TypeScript rejects a value not in the list. The lab's function also throws at runtime for plain JavaScript callers.

    A compound rule, such as the extra btn-danger-lg class, applies only when several axes have specific values at once, which keeps one-off exceptions in the design data.

    Two more decisions in the Button, both about the edges of the API:

    • Every native prop passes through. The props type is the button's own props plus the design's choices, so disabled and onClick work without the library listing them.
    • The caller's className is appended last. A caller can add a margin without a new prop. It can also undo the design, which is the cost of the escape hatch.

    React 19 lets a function component receive ref as a prop, and the docs say new components no longer need forwardRef, which they plan to deprecate in a future release. In the lab the Button forwards its ref without any wrapper, and a test confirms it reaches the DOM node.

    What the package promises

    Components are half the library. The other half is the package.json that decides what a consumer can do with it.

    Illustration 2 (realistic): the package fields for the storefront library. A sketch of the fields that matter (not the full file):

    {
      "name": "@shopstream/ui",
      "type": "module",
      "sideEffects": ["**/*.css"],
      "exports": {
        ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
        "./styles.css": "./dist/styles.css"
      },
      "peerDependencies": { "react": "^19.0.0" }
    }

    What each field promises, from the sources read for this lesson:

    • exports: when it is defined, "all subpaths of the package are encapsulated and no longer available to importers" (Node.js), and TypeScript, when it resolves through exports, will not resolve a subpath that is not listed. This is how an internal file stays internal. It is not absolute: Node.js notes a direct absolute path still loads the file. Introducing it into a published package "will likely be a breaking change" because paths that used to work stop working.
    • Condition order matters. Conditions are checked in object order, and "default" should come last. The "types" condition is a community convention that "should always be included first" according to the Node.js docs, and TypeScript always matches "types" and "default" when present.
    • sideEffects: a side effect is "code that performs a special behavior when imported, other than exposing one or more exports". false lets the bundler prune any unused file. An array lists the files that must be kept. Webpack's page states that tree shaking relies on ES2015 import and export, so the library should ship that syntax and not CommonJS.
    • peerDependencies: express compatibility with a host library. React belongs here, not in dependencies, so the app and the library share one copy. Since npm v7 peers are installed by default, and a peer can be marked optional in peerDependenciesMeta.

    Figure 3. What happens to an import

    flowchart TD accTitle: Resolving an import of the library accDescr: An app imports from the package name. If the path is the main entry or a listed subpath such as the stylesheet, it resolves. If the path is a file inside the package that is not listed in exports, resolution fails. Absolute paths into node_modules still work but are not part of the API. I["import ... from '@shopstream/ui/...'"] --> L{"Is the path in
    the exports map?"} L -->|"'.' (main entry)"| OK1["Resolves: public API"] L -->|"'./styles.css'"| OK2["Resolves: listed subpath"] L -->|"no: a file inside src/"| ERR["Fails to resolve:
    not exported"] ERR --> N["Absolute path into node_modules
    still loads: not supported"]

    How to read this: a library chooses its public API by listing it. Everything else is an error for a normal import, and an unsupported hack for the rest.

    Test the surface like a contract

    A public API changes only on purpose. The lab has a test that lists the exported names, so adding or removing one fails the test until someone edits the list:

    expect(Object.keys(library).sort()).toEqual(["Button", "Tabs", "buttonVariants", "defineVariants"]);

    Other tests check that the internal helpers are not exported, that package.json has one entry point, and that no source file imports a stylesheet while sideEffects is false. By Semantic Versioning, adding an export is a minor change and removing one is a major change, so this list is what a reviewer reads. The next lesson, Design System Governance and Versioning, builds on that.

    Build it

    Goal. Run the pure core and the thin React components together and see each layer tested where it is cheapest.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm).

    cd examples/frontend
    pnpm install
    cd labs/component-library-core
    pnpm test           # 42 tests
    node src/demo.ts

    Steps.

    1. Run the tests. Most are in core.test.ts (plain asserts), not in react.test.tsx (rendering).
    2. Run the demo and compare it with the output below.
    3. In section 2, ArrowDown on a horizontal list returns the same object, so the page can still scroll. In manual mode, focus and selection differ until Enter.
    4. In section 3, only the focused tab has tabIndex=0.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    Component library core: design choices as data, keyboard rules as a reducer
    
    === 1. Variants: named choices in, one class string out
    {}                                 -> btn btn-primary btn-md
    {"variant":"secondary"}            -> btn btn-secondary btn-md
    {"size":"sm"}                      -> btn btn-primary btn-sm
    {"variant":"danger","size":"lg"}   -> btn btn-danger btn-lg btn-danger-lg
    {"variant":"danger","size":"sm"}   -> btn btn-danger btn-sm
    {"variant":"loud"} (cast past the types) -> RangeError: unknown value "loud" for variant "variant"
    
    === 2. Tabs: the same keys, two activation modes
    
    automatic (selecting follows focus)
    start              focused=details  selected=details
    key "ArrowRight"   focused=reviews  selected=reviews
    key "ArrowRight"   focused=shipping selected=shipping
    key "ArrowRight"   focused=details  selected=details
    key "End"          focused=shipping selected=shipping
    key "ArrowDown"    focused=shipping selected=shipping  (not handled: same object)
    key "Home"         focused=details  selected=details
    
    manual (Enter or Space selects)
    start              focused=details  selected=details
    key "ArrowRight"   focused=reviews  selected=details
    key "ArrowRight"   focused=shipping selected=details
    key "Enter"        focused=shipping selected=shipping
    
    === 3. Attributes the core hands to the thin React layer (focused: reviews)
    t-tab-details    role=tab aria-selected=false tabIndex=-1 controls=t-panel-details
    t-tab-reviews    role=tab aria-selected=true  tabIndex= 0 controls=t-panel-reviews
    t-tab-shipping   role=tab aria-selected=false tabIndex=-1 controls=t-panel-shipping
    
    === 4. What the package declares
    exports:     {".":"./src/index.ts"}
    sideEffects: false
    internal barrel (runtime names): buttonVariants, createTabs, defineVariants, joinClasses, panelAttributes, tabAttributes, tabsReducer

    What the lab does not show. It does not render in a browser, apply any CSS (the class names are made up), run a screen reader or build a package, so it says nothing about bundle size or how a bundler treats sideEffects. It implements part of the tabs pattern, not all of it.

    Break it. In src/core/tabs.ts, in the ArrowRight branch of tabsReducer, replace (at + 1) % ids.length with Math.min(at + 1, ids.length - 1). The wrap-around tests fail, in the core and in the React tests. Revert it and run the tests again.

    Trade-offs

    Choice Gain Cost
    Pure core plus thin React layer Fast exact tests Two places to look for behaviour
    Named variant axes Impossible combinations rejected New design needs a release
    className escape hatch Callers solve one-off needs Callers can undo the design
    One entry point via exports Internals change freely Consumers lose deep imports
    Surface test API changes are deliberate An extra list to update

    In practice: three buttons that drifted apart

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront has three apps built by three teams. Each copied a Button and a Tabs from the first app a year ago and then changed them. Checkout's tabs support Home and End, the account app's do not, and the product page's buttons have a danger style that the others spell differently. A designer asks for a new button size, which means three changes in three repositories.

    Starting architecture

    Figure 4. Starting point: three copies

    Starting architecture: each app owns its own copy of Button and TabsDesign file to Product page (re-copied by hand); Design file to Checkout (re-copied by hand); Design file to Account (re-copied by hand)Product page: own Button, TabsProduct pageown Button, TabsCheckout: own Button, TabsCheckoutown Button, TabsAccount: own Button, TabsAccountown Button, TabsDesign file: the intended lookDesign filethe intended lookre-copied by handre-copied by handre-copied by hand

    How to read this: nothing connects the three copies except a person looking at a design file.

    Options considered

    Option What it fixes What it costs Risk
    Keep copies, add a style guide Cheap Copies still drift The guide is not enforced
    Shared library, everything exported Quick to start Apps import internals Every refactor is a breaking change
    Shared library with a pure core, thin React and one entry point One implementation, an API that can be tested and versioned Package setup, a release process A wrong sideEffects or exports fails in production builds

    The decision

    Field Decision record
    Context Three apps use diverging copies of the same two components.
    Decision Create one package with a pure core, thin React components and a single entry point (exports has only . and the stylesheet). Add a surface test. List the stylesheet in sideEffects.
    Consequences, good One implementation of keyboard rules, tested without a browser. Internals can be refactored without a major release.
    Consequences, bad Apps wait for a library release to get a change, and there is a release process to run.
    Revisit when Several teams need different versions at once, or the library grows past what one team can review.

    Rollout and verification

    1. Extract the more complete copy first, with its tests moved to the core where possible.
    2. Move one app and compare its screens before and after, then the others.
    3. Add the surface test and a build check that a consumer app's production build includes the stylesheet.

    The 2 a.m. failure

    Illustration 3 (failure): The library's Button starts importing its own stylesheet, and an earlier change set "sideEffects": false for the whole package. Everything looks right in development. After release, the production build of one app has unstyled buttons: the bundler treats the stylesheet as having no effect and prunes it, which is the case the webpack documentation describes with its awesome-ui example (illustrative; a real bundler setup may differ).

    First three checks: (1) compare the production CSS with the development CSS; (2) read sideEffects in the library's package.json; (3) check whether the stylesheet is imported by a file or listed as an export. Mitigation: change sideEffects to list the CSS files and release a patch. Follow-up: add a consumer build to CI that asserts the stylesheet is present, and keep the surface test's no-stylesheet-import check honest, as the lab does for false.

    Architect's notes

    • Put rules in pure functions first. If a rule needs document, ask whether it is a rule or an effect.
    • Export less than you can. Adding an export later is a minor change; removing one is a major change.
    • Treat package.json as code, with review and tests.
    • Decide the keyboard model once per component, and write it down.

    Common mistakes

    • Exporting internals because a test or one team needed them.
    • Putting React in dependencies, which can load two copies of it.
    • "sideEffects": false with CSS imports, which breaks only in production builds.
    • Adding exports to a published package without a major version, which blocks deep imports consumers already use.

    Key takeaways

    • A library has three layers: a pure core, thin React components and a public entry point.
    • A reducer is pure, so it can be tested in isolation; return the same object for an unhandled event.
    • Variants as data reject combinations nobody designed.
    • exports encapsulates internal paths; sideEffects tells bundlers what they may prune; React belongs in peerDependencies.
    • A surface test makes API changes deliberate.
    • jsdom tests prove roles and focus; they do not prove screen reader output or styling.

    Practice exercises

    Exercise 1 — Starter (45 min): In the lab, add a size of xl to buttonVariants and write the core test first. Then check which tests and which export lists need to change.

    Exercise 2 — Intermediate (2 hours): Add a Badge component with a tone axis built with defineVariants. Export it, update the surface test, and say whether this is a minor or a major change.

    Exercise 3 — Advanced (half day): Add disabled tabs to the core: arrows skip them and Home goes to the first enabled tab. Write the reducer tests before the React change.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments