Storybook earns its place in a React codebase for one reason: it makes the component the unit of design review. Inside the isolated frame a button can be rendered in every variant, size, disabled state, loading state and error state without booting the whole application, standing up a router or seeding a database. That isolation is also what turns Storybook into a testing surface, because the same story that shows a designer the hover treatment can drive an interaction test, an accessibility scan and a screenshot comparison. Teams that treat stories as a gallery end up with documentation nobody trusts. Teams that treat each story as a specification get a component library whose edges are visible before the feature work begins, and a place to reproduce a bug report without reproducing the application around it.
đĄOne story, one question
If you cannot say what a story demonstrates in a single sentence, it is probably two stories. Names such as "danger button with a long label wraps" teach a reader what to look at; names such as "example 4" teach nothing and age badly.
A story is a specification, not a screenshot
Start by enumerating the states a component can occupy rather than the props it happens to accept. A form field has a default, a focused, a filled, an invalid, a disabled and a read only state, and each of those usually has a variant with helper text. A modal has closed, open, open with a long title, and open while the underlying page is still loading. Write a story for every state a user can actually reach, and delete any story whose state cannot be reached, because unreachable stories are fiction that someone will eventually screenshot.
The second half of the specification is content variance. Short labels hide overflow bugs, long labels reveal them. Empty lists, lists of one, lists of two hundred, names with emoji, emails with plus addresses, prices with four decimal places: these are the inputs that break layouts and truncation logic. A story library that only renders the happy path documents an application that does not exist.
// Button.stories.jsx
import { fn } from '@storybook/test';
import { Button } from './Button';
export default {
title: 'Design System/Button',
component: Button,
tags: ['autodocs'],
argTypes: {
variant: {
control: 'inline-select',
options: ['primary', 'secondary', 'danger'],
description: 'Visual weight and the semantic colour of the action',
},
size: { control: 'inline-select', options: ['sm', 'md', 'lg'] },
onClick: { action: 'clicked', table: { disable: true } },
},
};
export const Primary = {
args: { children: 'Save changes', variant: 'primary', onClick: fn() },
};
export const Disabled = {
args: { children: 'Save changes', variant: 'primary', disabled: true },
};
export const DangerWithLongLabel = {
args: {
children: 'Delete this project and all of its history',
variant: 'danger',
onClick: fn(),
},
};
Two habits in that file pay off later. The tag asking for automatic documentation means a reference page is generated from the same metadata, and the callback is replaced with a recording function so a reviewer can click the button in the sidebar and see the event payload without writing a test first.
Controls, argTypes and the addons that matter
Controls are the sidebar that lets a reviewer change props live. They are a communication tool more than a testing tool: someone in a design review can flip the variant dropdown, type a fifty character label and see the result in two seconds instead of asking the engineer to add a temporary story. Declare controls in argTypes alongside descriptions, because the description travels into the generated docs.
| Addon | What it adds | When it earns its place |
|---|---|---|
| Controls | Live prop editing with type hints | Reviews where states are explored rather than asserted |
| Actions | Logged events with payloads | Proving a callback fired with the arguments the API promised |
| Interactions | Play functions with a replayable timeline | Behaviour tests that should not need a second harness |
| Accessibility | An axe scan of every rendered story | Contrast and naming regressions caught at story level |
| Viewport and backgrounds | Breakpoints and surface colours | Checking a token against light, dark and narrow layouts |
| Autodocs | Generated reference pages from metadata | Keeping prop tables honest without manual edits |
Restraint here matters. Every addon you enable slows the manager bundle and adds configuration that someone must maintain, so adopt them when the question appears rather than enabling the full set on day one. Where a control actively breaks rendering, such as a children prop that expects a function, disable it and document the reason in the argType description rather than letting a reviewer destroy the example.
Interaction tests with play functions
A play function runs after the story renders and drives the canvas with the same event synthesis a user would generate. Because stories render inside a frame, focus, keyboard handling and portal targets behave the way they do in the application, which makes play functions a credible place to test dialogs, menus and composite widgets. The interactions addon records each step, so a failing story shows the sequence of clicks and keys rather than a stack trace.
// ConfirmDialog.stories.jsx
import { expect, fn, userEvent, within } from '@storybook/test';
import { ConfirmDialog } from './ConfirmDialog';
export default {
title: 'Overlays/ConfirmDialog',
component: ConfirmDialog,
};
export const ClosesWhenConfirmed = {
args: {
title: 'Discard draft',
confirmLabel: 'Discard',
onConfirm: fn(),
onCancel: fn(),
children: 'Your unsaved changes will be lost.',
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: /discard/i }));
await expect(args.onConfirm).toHaveBeenCalledTimes(1);
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
},
};
export const EscapeCancels = {
args: { onConfirm: fn(), onCancel: fn() },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const dialog = canvas.getByRole('dialog');
await userEvent.type(dialog, '{Escape}');
await expect(args.onCancel).toHaveBeenCalledTimes(1);
},
};
The test runner package executes every play function in continuous integration, which means the same file powers the documentation, the manual exploration and the regression gate. That is the economy Storybook is really selling: one artifact, three uses.
Visual regression without screenshot archaeology
Screenshot comparison catches what text assertions cannot: a token change that renders white text on a pale background, a card that overlaps its neighbour at a narrow viewport, a label that clips when the font loads late. It is also the check most likely to drown in noise, so the environment has to be pinned. Run comparisons in the same container your continuous integration uses, freeze anything time dependent, and disable animation, because font hinting and transition frames differ between machines by enough to fail every run.
Practical discipline is short. Keep a small pixel threshold so anti-aliasing does not register as a change, review each diff in the pull request rather than accepting in bulk, and separate structural comparisons from content comparisons so a marketing copy change does not invalidate a layout baseline. When a baseline must change, change it in a pull request where the diff is visible and the reason is written down.
Documentation that cannot drift from the code
Manual prop tables rot the moment a prop is renamed, because nothing forces the edit. Generating them from TypeScript types and argType descriptions removes the failure mode entirely, and autodocs makes the story file the single source of truth. Prose documentation still has a place, but it should explain decisions rather than restate signatures: why the component is controlled, what it refuses to do, which accessibility contract it keeps.
Reserve one page for usage guidance that no story can express, such as the rule that a card grid must be wrapped in a list element for screen readers to announce a count. Then link the stories as the live examples. A reader who sees the guidance and can immediately play with the code beside it is far more likely to follow it than one who reads a snippet copied from a pull request three quarters ago.
Tokens, providers and network state in the frame
Stories only stay isolated if the surrounding application is represented honestly. Set up the preview entry file to wrap every story with the providers the real app uses: the theme provider that supplies design tokens, the router stub that supplies location, the query client with a warm cache, and the toast host that renders notifications. When each story must configure those wrappers by hand, half the file becomes ceremony and the other half renders a component that is not actually the one in production.
// .storybook/preview.js
import { ThemeProvider } from './theme/ThemeProvider';
import { ToastHost } from './toast/ToastHost';
import { makeQueryClient } from './queryClient';
import { QueryClientProvider } from '@tanstack/react-query';
const queryClient = makeQueryClient();
export const decorators = [
(Story) => (
<ThemeProvider>
<QueryClientProvider client={queryClient}>
<Story />
<ToastHost />
</QueryClientProvider>
</ThemeProvider>
),
];
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: { expanded: true },
};
For anything that touches the network, prefer an interceptor that serves fixtures at the request layer over mocking your own modules. The component then imports the same code it ships with, and a story can show the loading, empty, error and populated variants by swapping a handler rather than a module. Keep those handlers next to the stories they serve, and name them after the scenario: a story for a failed save should read like a failure case, not like a fixture index number.
Common Mistakes
Writing one story that renders the component with default props and calling the coverage complete
Fix: Enumerate reachable states and content edge cases, and delete stories for states the application can never enter.
Asserting on internal state inside a play function
Fix: Drive the canvas with user events and assert on visible outcomes, roles and names, exactly as in a component test.
Accepting every screenshot diff during review
Fix: Pin the rendering environment, keep thresholds small, and review diffs individually so a regression never becomes the baseline by reflex.
Letting the preview file drift from the real application providers
Fix: Configure providers once in the preview entry so every story renders inside the same context the production app uses.
Best Practices
- Name each story after the question it answers, because the sidebar becomes a readable catalogue of component behaviour
- Declare controls and descriptions in argTypes so the generated reference page stays accurate without manual edits
- Add addons when a question appears rather than on day one, since every addon slows the manager and adds configuration to maintain
- Record callbacks with a spy function so a reviewer can click in the sidebar and inspect the payload immediately
- Run the test runner in continuous integration so play functions and accessibility scans gate every pull request
Key Takeaways
- Stories are specifications: enumerate reachable states and awkward content, and drop anything a user cannot reach
- Controls exist for exploration and review, while play functions turn the same story into an executable behaviour test
- Visual comparisons only stay trustworthy when the rendering environment, animation and clock are pinned
- Docs generated from types and argTypes cannot drift, so keep prose for decisions and let stories carry the examples
- Configure providers and network fixtures once in the preview entry so stories render the code that actually ships