Storybook Guide
The complete reference for Storybook — the UI component workshop used by Netflix, Airbnb, and thousands of teams. Covers CSF3 stories, args, decorators, play functions, addons, and visual regression testing.
What is Storybook?
Storybook is an open-source workshop for building, documenting, and testing UI components in isolation. Instead of navigating through your application to reach a specific component state (say, an error state deep in a form flow), Storybook lets you define every state as a "story" — a named configuration with specific props — and jump directly to any state instantly.
This isolation-first approach transforms how teams build design systems. Designers can review components in every state without a developer running the full app. New developers can explore the component library as living documentation. QA engineers can verify edge-case states that are hard to reproduce in the real application. And with Chromatic or other visual testing tools, every pixel change is caught automatically in CI.
Installation
# Automatic setup (detects your framework) npx storybook@latest init # For an existing React + Vite project npx storybook@latest init --type react # Run Storybook npm run storybook # http://localhost:6006 # Build static Storybook for deployment npm run build-storybook # Run interaction tests headlessly npx test-storybook
Writing Stories: CSF3 Format
Component Story Format 3 (CSF3) is the standard way to write Storybook stories. A story file has one default export (component metadata) and multiple named exports (individual states).
// src/components/Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
// Default export: component metadata
const meta: Meta<typeof Button> = {
title: 'UI/Button', // Sidebar navigation path
component: Button,
tags: ['autodocs'], // Auto-generate Docs page
argTypes: {
variant: {
control: 'select',
options: ['primary', 'secondary', 'danger'],
},
size: { control: 'radio', options: ['sm', 'md', 'lg'] },
},
};
export default meta;
type Story = StoryObj<typeof Button>;
// Named exports: individual stories
export const Primary: Story = {
args: { label: 'Click me', variant: 'primary', size: 'md' },
};
export const Secondary: Story = {
args: { label: 'Cancel', variant: 'secondary', size: 'md' },
};
export const Danger: Story = {
args: { label: 'Delete', variant: 'danger', size: 'md' },
};
export const Loading: Story = {
args: { label: 'Saving...', variant: 'primary', disabled: true, loading: true },
}; Decorators: Global Context Providers
// .storybook/preview.tsx — applies to ALL stories
import { ThemeProvider } from '../src/theme';
import type { Preview } from '@storybook/react';
const preview: Preview = {
decorators: [
(Story) => (
<ThemeProvider theme="light">
<div style={{ padding: '1rem' }}>
<Story />
</div>
</ThemeProvider>
),
],
parameters: {
backgrounds: {
default: 'light',
values: [
{ name: 'light', value: '#ffffff' },
{ name: 'dark', value: '#1a1a1a' },
],
},
},
};
export default preview; Play Functions: Interaction Testing
// LoginForm.stories.tsx
import { within, userEvent, expect } from '@storybook/test';
export const FilledAndSubmitted: Story = {
args: { onSubmit: fn() },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
// Simulate user interactions
await userEvent.type(canvas.getByLabelText('Email'), '[email protected]');
await userEvent.type(canvas.getByLabelText('Password'), 'secret123');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
// Assert the outcome
await expect(args.onSubmit).toHaveBeenCalledWith({
email: '[email protected]',
password: 'secret123',
});
},
};
export const ValidationErrors: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.getByText('Email is required')).toBeVisible();
},
}; Key Features
- Isolated development — build components without running the full application
- Controls addon — edit any prop interactively in the UI without code changes
- Docs addon — auto-generate API documentation from TypeScript types and JSDoc
- Accessibility addon — axe-core audit runs on every story automatically
- Play functions — interaction tests that run in CI via test-storybook
- Chromatic integration — pixel-perfect visual regression on every commit
- Framework support — React, Vue, Angular, Svelte, Web Components, Solid
Comparison: Storybook vs Alternatives
| Feature | Storybook | Ladle | Histoire | Docz |
|---|---|---|---|---|
| Framework support | All major | React only | Vue + Svelte | React |
| Build speed | Moderate (Webpack) | Fast (Vite) | Fast (Vite) | Moderate |
| Addon ecosystem | 200+ addons | Minimal | Minimal | Limited |
| Play functions | Yes | No | No | No |
| Community size | Very large | Small | Small | Small |
| Visual regression | Chromatic | DIY | Limited | No |
Pros & Cons
Pros
- Industry standard with massive adoption and community
- Supports every major UI framework
- Rich addon ecosystem (200+ addons)
- Play functions enable CI interaction testing
- Chromatic integration for visual regression
- Living documentation auto-generated from stories
Cons
- Slow build times with Webpack (Vite builder helps)
- Complex configuration for custom webpack setups
- Heavy dependency footprint
- Chromatic visual testing has a cost at scale
- Can diverge from real app environment
Frequently Asked Questions
What is Storybook and why do teams use it?▼
Storybook is an open-source tool for developing and documenting UI components in isolation. Rather than building components inside your full application (where dependencies, routing, and data fetching complicate things), Storybook provides a standalone workshop where each component state — called a 'story' — can be built, tested, and reviewed independently. Teams use it to build design systems, onboard new developers, run visual regression tests, and maintain living documentation.
What is the Component Story Format (CSF)?▼
CSF (Component Story Format) is the standard format for writing Storybook stories. CSF3 (the current version) uses a default export with metadata (component, title, decorators) and named exports for each story. Each named export is an object with an args property that defines the component's props. This declarative format is portable — it works with Storybook's addons, interaction testing, and tools like Chromatic for visual regression.
What are Storybook addons?▼
Addons extend Storybook's functionality. The most important built-in addons are: Controls (interactive prop editing in the Addons panel), Actions (log event callbacks like onClick), Docs (auto-generate documentation from JSDoc and stories), a11y (accessibility audit via axe-core), and Interactions (run user events and make assertions via play functions). Community addons cover styling, theming, internationalization, and integration with Figma.
What is a play function in Storybook?▼
A play function is an async function attached to a story that simulates user interactions after the component renders. It uses @storybook/test (a wrapper around Testing Library) to find elements and fire events. Play functions make stories interactive and testable — they run automatically in Storybook's UI and can be executed headlessly in CI via the test-storybook runner. This enables interaction testing without Cypress or Playwright.
What is Chromatic and how does it relate to Storybook?▼
Chromatic is a visual testing and review service built by the Storybook maintainers. It snapshots every story in every browser on every commit and shows you a visual diff for review. When a PR changes a component, Chromatic flags the visual change and requires a team member to accept or reject it — preventing accidental UI regressions. Chromatic also hosts your Storybook as a shareable URL for design review without a local setup.
How do I use decorators in Storybook?▼
Decorators are wrapper functions that add context to stories — themes, router providers, global state, or design tokens. Define decorators in .storybook/preview.ts (applies to all stories) or in the story file's default export (applies to that component's stories). Example: wrapping all stories with a ThemeProvider ensures components always render with the correct theme, eliminating the need to repeat setup in every story.
Related Products
on GumroadDevToolkit Starter Kit
A ready-to-deploy developer tools website with 12 built-in tools. Astro + Preact + Tailwind. Deploy to Cloudflare Pages for free. Built-in SEO, dark mode, and ad-ready layout.
Buy on Gumroad →DevPlaybook Interview Vault
210+ real technical interview questions with model answers, asked at Google, Meta, Amazon, Microsoft, Stripe, and Shopify. Covers Frontend (55), Backend (55), System Design (50), and DSA (50). Available in English and Traditional Chinese.
Buy on Gumroad →TypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad →You Might Also Need
UUID Generator
Free UUID generator. Generate UUID v1 (time-based), v4 (cryptographically random), or v5 (SHA-1 name-based) in bulk. Multiple output formats: standard, UPPERCASE, no-hyphens, braces. Pro: generate up
Open free tool →
UUID v7 Generator
Generate UUID v7 — the timestamp-ordered UUID format from RFC 9562. Sortable, database-friendly, ideal for distributed systems. Also generates UUID v4, ULID, nanoid. Extract timestamps from UUID v7. Runs in your browser.
Open free tool →
TanStack Query Config Builder
Configure TanStack Query (React Query v5) staleTime and gcTime visually. Generate QueryClient config and useQuery/useMutation TypeScript code with retry logic.
Open free tool →
More Free Tools
Related Articles
Building a Custom shadcn/ui Registry: Share Components Across Projects
Learn how to build and host a custom shadcn/ui component registry in 2026. Covers registry.json format, CLI installation, versioning, monorepo patterns, and when to choose a registry over npm packages.
shadcn/ui: The Complete Component Library Guide for 2026
Complete guide to shadcn/ui covering installation across Next.js, Vite, Remix, and Astro, theming with CSS variables, new 2025-2026 components, customization patterns, registry system, and comparison with Radix/MUI/Ant Design.
shadcn/ui vs Radix UI vs Headless UI vs Ark UI: The Definitive React Component Library Comparison 2026
An in-depth 2026 comparison of shadcn/ui, Radix UI, Headless UI, and Ark UI — covering customization, accessibility, bundle size, TypeScript support, and which library fits your React project best.
API Mocking for Frontend Development: Complete Guide (2025)
How to use API mocking to develop frontend apps without a real backend. Covers MSW, JSON Server, mock services in Postman, browser-based mock APIs, and testing strategies.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →