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
exportsandsideEffectsfields ofpackage.jsonpromise 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.
- 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.
- 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.
- The package file is part of the architecture. The
exportsfield decides which paths a consumer can import, andsideEffectstells 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
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
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
disabledandonClickwork without the library listing them. - The caller's
classNameis 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 throughexports, 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".falselets the bundler prune any unused file. An array lists the files that must be kept. Webpack's page states that tree shaking relies on ES2015importandexport, so the library should ship that syntax and not CommonJS.peerDependencies: express compatibility with a host library. React belongs here, not independencies, so the app and the library share one copy. Since npm v7 peers are installed by default, and a peer can be marked optional inpeerDependenciesMeta.
Figure 3. What happens to an import
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.
- Run the tests. Most are in
core.test.ts(plain asserts), not inreact.test.tsx(rendering). - Run the demo and compare it with the output below.
- In section 2,
ArrowDownon a horizontal list returns the same object, so the page can still scroll. In manual mode, focus and selection differ untilEnter. - 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
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
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
- Extract the more complete copy first, with its tests moved to the core where possible.
- Move one app and compare its screens before and after, then the others.
- 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.jsonas 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": falsewith CSS imports, which breaks only in production builds.- Adding
exportsto 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.
exportsencapsulates internal paths;sideEffectstells bundlers what they may prune; React belongs inpeerDependencies.- 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.
Related reading
In this course:
- Component Composition and API Design, shaping one component's props.
- Module Boundaries and Public APIs, the same idea inside an application.
- Monorepos and Shared Libraries, where a library like this usually lives.
- React Purity, Strict Mode and Refs, why render and reducer code must stay pure.
- CSS Architecture and Scaling, the layer beside the components.
Official documentation
- WAI-ARIA Authoring Practices: Tabs pattern and Developing a keyboard interface.
- React: Extracting state logic into a reducer and the React 19 release post.
- Node.js: Packages, the
exportsfield and conditions. - TypeScript: Modules reference,
exportsand thetypescondition. - webpack: Tree shaking, the
sideEffectsproperty. - npm: package.json and Semantic Versioning 2.0.0.