Sub topic 11
Shared UI Components and Design Systems
This chapter assumes you know React components, props, and hooks, and that you have read the earlier chapters on feature modules, public APIs, and component layers. Here we look at the shared/ui layer: what belongs in it, how to design its components, and when it grows into a design system.
What shared UI is for
Shared UI is the set of components that know how to look and behave, but know nothing about your business. A Button is shared UI. A CartSummary is not, because it knows what a cart is.
A useful test: could you copy the component into a different product without editing it? If yes, it belongs in shared/ui. If it imports from a feature, calls an API, or mentions a domain term such as "order" or "invoice", it belongs in a feature.
The dependency rule follows from this:
- Features may import from
shared/ui. shared/uimust never import from a feature.- Pages may import from both.
The diagram shows the allowed direction of imports.
What to put in shared UI
Good candidates are primitives and small composites:
- Primitives:
Button,Input,Checkbox,Badge,Spinner. - Layout helpers:
Stack,Grid,Container. - Overlay components:
Modal,Tooltip,Popover. - Composites with no domain knowledge:
DataTable,Tabs,Pagination.
Poor candidates are components you only suspect you might reuse. Wait until a second feature needs the same component, then move it. Moving a component down is cheap. Untangling a "shared" component that every feature bent in a different direction is not.
Folder layout
Give each component its own folder, with the same colocation rules you use in features.
src/shared/ui/
Button/
Button.tsx
Button.test.tsx
Button.module.css
index.ts
Modal/
Modal.tsx
Modal.test.tsx
index.ts
index.tsThe top-level shared/ui/index.ts re-exports every component, so features import from one place:
// src/shared/ui/index.ts
export { Button } from "./Button";
export type { ButtonProps } from "./Button";
export { Modal } from "./Modal";// in a feature
import { Button, Modal } from "@/shared/ui";Designing component APIs
Shared components are used in many places, so their props are hard to change later. Design them with care.
Extend native element props
A button should accept everything a <button> accepts. Otherwise people open pull requests to add aria-label, onKeyDown, or data-testid one at a time.
import type { ButtonHTMLAttributes } from "react";
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
variant?: "primary" | "secondary" | "danger";
size?: "sm" | "md" | "lg";
};
export function Button({
variant = "primary",
size = "md",
type = "button",
className,
...rest
}: ButtonProps) {
const classes = ["btn", `btn-${variant}`, `btn-${size}`, className]
.filter(Boolean)
.join(" ");
return <button type={type} className={classes} {...rest} />;
}Two details matter here. The default type="button" prevents accidental form submission, since the HTML default is submit. And ...rest is spread last, so callers can add attributes without the component listing each one.
Prefer variants over booleans
A union such as variant: "primary" | "danger" makes impossible states impossible. Props like isPrimary and isDanger allow isPrimary isDanger together, and you have to decide what that means.
Prefer composition over configuration
When a component grows many props that control its inner layout, switch to children or compound components.
// Configuration: every new need adds a prop
<Card title="Orders" subtitle="Last 30 days" actionLabel="Export" onAction={exportCsv} />
// Composition: the caller decides the content
<Card>
<Card.Header>Orders</Card.Header>
<Card.Body>...</Card.Body>
<Card.Footer>
<Button onClick={exportCsv}>Export</Button>
</Card.Footer>
</Card>Composition keeps the shared component stable. A new layout needs no new prop.
Forward refs when you wrap a DOM element
Parents sometimes need a ref to focus an input or measure a node. In React 19, ref is a regular prop for function components. In earlier versions, wrap the component with forwardRef. Check which version your project uses before copying examples.
Keep domain logic out
The most common failure in shared UI is leaking domain knowledge. Compare these two:
// Bad: shared component knows about the cart feature
import { useCart } from "@/features/cart";
export function AddButton({ productId }: { productId: string }) {
const { add } = useCart();
return <button onClick={() => add(productId)}>Add to cart</button>;
}
// Good: shared component takes behavior from the caller
export function Button(props: ButtonProps) { /* ... */ }
// The feature supplies the behavior
<Button onClick={() => add(productId)}>Add to cart</Button>The first version creates an import from shared to a feature. It also makes the lint boundary rules from the enforcement chapter fail, which is how you want to find it.
Data fetching and global state follow the same rule. A shared Select receives options as a prop. It does not fetch them.
Styling strategy
Shared components need a styling approach that does not leak. Common options:
| Approach | Strength | Watch out for |
|---|---|---|
| CSS Modules | Scoped class names, no runtime cost | Theming needs CSS variables |
| Utility CSS (Tailwind) | Fast, consistent spacing and color scale | Long class strings, need a `cn` helper to merge overrides |
| CSS-in-JS with runtime | Props-driven styles, theming built in | Runtime cost, server rendering setup |
| Zero-runtime CSS-in-JS | Typed styles, no runtime cost | Build tool integration |
Whichever you pick, use design tokens: named values for color, spacing, and type size. With CSS variables:
:root {
--color-primary: #1d4ed8;
--color-danger: #b91c1c;
--space-2: 0.5rem;
--radius-md: 0.375rem;
}
.btn-primary {
background: var(--color-primary);
border-radius: var(--radius-md);
padding: var(--space-2) calc(var(--space-2) * 2);
}Tokens let you change a brand color in one place, and they make dark mode a matter of redefining variables.
Accessibility belongs here
Shared UI is the cheapest place to get accessibility right, because a fix applies everywhere at once. For each interactive component, check:
- Keyboard operation: can you reach and use it with Tab, Enter, Space, Escape, and arrow keys?
- Focus management: does a modal trap focus and return it to the trigger when closed?
- Semantics: do you use a real
<button>instead of a clickable<div>? - Labels: does every input have an accessible name?
Modals, menus, comboboxes, and date pickers are hard to build correctly. Consider headless libraries such as Radix UI or React Aria. They supply behavior and accessibility, and you supply the styling.
Documenting and testing shared UI
Because many features depend on shared components, they need more care than feature code.
- Write a unit test per component for its variants, disabled state, and keyboard behavior.
- Use a component workshop such as Storybook to show every variant in isolation. It doubles as documentation and lets designers review changes.
- Add visual regression tests if the design is stable enough to justify the maintenance.
From shared folder to design system
A shared/ui folder becomes a design system when it has more than components: tokens, usage guidelines, documented patterns, and an owner. Use this table to judge where you are.
| Stage | Signs | Typical home |
|---|---|---|
| Shared folder | One app, a few primitives, no docs | `src/shared/ui` |
| Internal library | Several apps or a dedicated maintainer, a component workshop | Workspace package in a monorepo |
| Design system | Tokens, versioned releases, design files, contribution process | Published package with a team |
Do not start at the last row. A design system is a product with users, and it needs staffing. Move to the next stage only when the pain is real, for example two applications copying the same components. The monorepo chapter covers the packaging step.
Common mistakes
- Adding a prop for every request, until
Buttonhas 25 props. Push back, or use composition. - Importing a feature from shared UI. The layering rule above forbids it.
- Copying a shared component into a feature "just to change one thing." Add a variant or a slot instead, or accept that the component is feature-specific.
- Skipping the index file, so features import
@/shared/ui/Button/Buttonand depend on internals. - Hard-coding colors and spacing, which defeats theming.
Summary
Shared UI holds domain-free components that every feature can import and that import nothing from features. Design their APIs to extend native props, use variants and composition, and keep behavior in the caller's hands. Use tokens for styling, build in accessibility, and test and document the components. Promote the folder to a library or design system only when several consumers justify the cost.
Exercise
A teammate adds OrderStatusBadge to src/shared/ui because it renders a colored badge. It maps the order statuses "paid", "shipped", and "refunded" to colors. What is wrong, and how would you fix it?
Show answer
The component knows the domain concept of order status, so it is not domain-free and does not belong in shared UI. Split it in two. Keep a generic Badge in shared/ui with a variant prop such as "success", "info", or "warning". Put OrderStatusBadge in the orders feature, where it maps each status to a variant and renders Badge.
Exercise
Why does the Button example spread ...rest after setting its own props, and why default type to "button"?
Show answer
Spreading ...rest lets callers pass any native button attribute, such as aria-label or disabled, without the component declaring each one. Defaulting type to "button" avoids the HTML default of "submit", which would submit a surrounding form on every click. Callers who want a submit button pass type="submit".
Exercise
A shared UserSelect component calls useUsers() from the users feature to load its options. Describe two problems this causes and rewrite its props so the problems go away.
Show answer
First, it makes shared/ui import from a feature, which reverses the dependency direction and breaks boundary lint rules. Second, it ties the component to one data source, so it cannot be reused or tested without the users feature and a server-state provider. Make it a generic Select with props like options: { value: string; label: string }[], value, and onChange. The users feature calls useUsers() and passes the mapped options in.