Skip to content
Homeβ€Ί JavaScriptβ€Ί How to Build a Design System with shadcn/ui, Tailwind & Radix

How to Build a Design System with shadcn/ui, Tailwind & Radix

Where developers are forged. Β· Structured learning Β· Free forever.
πŸ“ Part of: React.js β†’ Topic 30 of 32
Production guide to building a scalable, accessible design system using shadcn/ui, Tailwind CSS v4, and Radix Primitives.
πŸ”₯ Advanced β€” solid JavaScript foundation required
In this tutorial, you'll learn
Production guide to building a scalable, accessible design system using shadcn/ui, Tailwind CSS v4, and Radix Primitives.
  • shadcn/ui gives you source ownership β€” treat it as a codebase to maintain, not a package to consume
  • Token synchronization between CSS variables and Tailwind is non-negotiable β€” automate with a build script
  • Radix handles accessibility primitives β€” your job is to not break them through customization
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
⚑Quick Answer
  • shadcn/ui is a copy-paste component library built on Radix Primitives and Tailwind CSS
  • Radix provides accessible, unstyled primitives; Tailwind handles styling; shadcn/ui ships the integration
  • Design tokens live in CSS custom properties and @theme directives for consistent theming
  • Components are installed via npx shadcn@latest add β€” copied into your codebase, not as node_modules dependency
  • This architecture gives you full ownership: modify any component without fighting upstream updates
  • Biggest mistake: treating shadcn/ui like a black-box npm package instead of a codebase you own
🚨 START HERE
shadcn/ui Quick Debug Reference
Immediate actions for common design system failures
🟑Tailwind classes not applying to component
Immediate ActionVerify source paths
Commands
grep -r '@source' src/globals.css || cat tailwind.config.js | grep content
npx @tailwindcss/cli -i ./src/globals.css --watch
Fix NowAdd missing directory to @source (v4) or content array (v3)
🟑Radix Dialog not trapping focus
Immediate ActionCheck for multiple Dialog.Portal instances
Commands
grep -r 'Dialog.Portal' src/
grep -r 'FocusScope' src/
Fix NowEnsure single Portal per Dialog and no conflicting FocusScope wrappers
🟑CSS variables not resolving in production
Immediate ActionVerify :root variable definitions exist
Commands
grep -r ':root' src/app/globals.css
Open DevTools > Elements > :root > Computed properties
Fix NowCopy variable definitions from ui.shadcn.com/docs/installation
Production IncidentTheme Tokens Drift Across 12 Micro-FrontendsA fintech company deployed shadcn/ui across 12 micro-frontends. Six months later, buttons rendered in four different shades of primary blue.
SymptomVisual inconsistency across product surfaces β€” identical components rendered differently depending on which team deployed last. QA flagged 47 color discrepancies in a single sprint.
AssumptionEach team assumed the shared tailwind.config.js was the source of truth. Nobody verified that the CSS custom properties matched across deployments.
Root causeTeams forked the theme configuration into local overrides during urgent feature work. The shared config had no linting to enforce token compliance. CSS custom properties diverged silently because Tailwind compiles at build time β€” no runtime validation exists.
FixExtracted all design tokens into a dedicated npm package: @thecodeforge/design-tokens. Added a CI lint step that parses CSS variables and Tailwind theme, failing builds on drift. Implemented a visual regression suite with Chromatic that caught pixel-level token mismatches.
Key Lesson
Design tokens must be a single publishable artifact, not a shared config fileBuild-time compilation means no runtime safety β€” enforce token consistency in CIVisual regression testing catches what code review misses
Production Debug GuideCommon symptoms when shadcn/ui components misbehave in production
Components render with no styles after deployment→Tailwind v4: Check @source directives in globals.css. Tailwind v3: Check content paths in tailwind.config.js. Run: npx @tailwindcss/cli -i ./src/globals.css -o /tmp/test.css
Radix portal components render behind modals or overlays→Verify z-index stacking context. Radix Dialog uses z-50 by default. Check for conflicting position:relative parents that create new stacking contexts.
Theme switching causes flash of unstyled content→Ensure theme script runs before React hydration. Add blocking script in <head> that sets class before paint (see Theming section).
Custom component overrides break after shadcn/ui update→Diff the component source against upstream. Run: npx shadcn@latest diff button. Review breaking changes before merging.

Design systems fail when teams choose between flexibility and consistency. Most component libraries force a tradeoff: accept their design decisions or fight the abstraction layer. shadcn/ui, Radix Primitives, and Tailwind CSS eliminate this tradeoff.

Radix handles accessibility, keyboard navigation, and focus management β€” the hardest parts of UI component engineering. Tailwind provides utility-first styling with a configurable design token layer. shadcn/ui merges both into production-ready components you install directly into your source tree.

This guide covers building a scalable design system from these primitives for 2025+. We will architect tokens for Tailwind v3 and v4, extend components for RSC, enforce consistency, and handle the production failures teams hit when scaling beyond a prototype.

Architecture: Why shadcn/ui Differs from Traditional Component Libraries

Traditional component libraries like Material UI or Chakra ship as npm packages. You import them, configure a theme provider, and accept their component API surface. When the library updates, you update. When their design decisions conflict with yours, you fight the abstraction.

shadcn/ui inverts this model. The CLI copies component source code directly into your project. You own every line. There is no node_modules dependency to update β€” you run npx shadcn@latest diff to see what changed upstream, then merge manually.

This architecture has three implications for design systems:

  1. Full ownership: Every component is yours to modify, extend, or replace
  2. No version lock-in: You control when and how to incorporate upstream changes
  3. Explicit dependencies: Radix Primitives and Tailwind are your only runtime dependencies

The tradeoff is maintenance burden. You are responsible for keeping components current. But for teams building a design system that must outlive any single library's roadmap, this tradeoff favors long-term control.

terminal Β· BASH
12345678910
# Install shadcn/ui components into your project
npx shadcn@latest init

# Components are copied to your components/ui directory
npx shadcn@latest add button
npx shadcn@latest add dialog
npx shadcn@latest add card

# Check for upstream changes without applying
npx shadcn@latest diff button
Mental Model
The Ownership Mental Model
shadcn/ui is a generator, not a dependency β€” you are maintaining a fork, not consuming an API.
  • Traditional libraries: you consume an API surface and fight abstraction leaks
  • shadcn/ui: you own the source code and merge upstream changes selectively
  • This is closer to forking an OSS project than installing a package
  • The maintenance cost is real but the control is absolute
πŸ“Š Production Insight
Teams treating shadcn/ui as a black-box dependency hit walls when customization exceeds the API surface.
Ownership means responsibility β€” assign a maintainer for your component directory.
Run npx shadcn@latest diff in CI to surface upstream changes before they become surprises.
🎯 Key Takeaway
shadcn/ui trades maintenance burden for absolute control.
This tradeoff only pays off when your design system must outlive the library's roadmap.
If you cannot commit to maintaining component source code, use a traditional library instead.
When to Use shadcn/ui vs Traditional Libraries
IfNeed rapid prototyping with minimal customization
β†’
UseUse shadcn/ui defaults β€” install and ship
IfBuilding a design system that must last 3+ years
β†’
UseUse shadcn/ui with dedicated token architecture and component ownership model
IfTeam lacks capacity to maintain component source code
β†’
UseUse a traditional library like Radix Themes or MUI with theme customization
IfNeed framework-agnostic components (Vue, Svelte, etc.)
β†’
UseUse Radix Primitives directly β€” shadcn/ui is React-only (use shadcn-vue or shadcn-svelte ports)

Token Architecture: Building the Foundation

A design system is only as strong as its token layer. Tokens are the atomic decisions β€” colors, spacing, typography, radii β€” that propagate through every component. Get tokens wrong and you will fight inconsistencies forever.

With shadcn/ui and Tailwind, tokens live in CSS custom properties. Tailwind v4 uses @theme directives, v3 uses tailwind.config.js β€” both must reference the same variables.

Tailwind v4 (recommended 2025+): ```css / app/globals.css / @import "tailwindcss"; @source "../components/*/.{ts,tsx}";

@theme { --color-background: hsl(0 0% 100%); --color-foreground: hsl(222.2 84% 4.9%); --color-primary: hsl(222.2 47.4% 11.2%); --color-primary-foreground: hsl(210 40% 98%); }

@layer base { :root { --radius: 0.5rem; } .dark { --color-background: hsl(222.2 84% 4.9%); } } ```

Tailwind v3 (legacy): ``css / globals.css / @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --primary: 222.2 47.4% 11.2%; } } ` `javascript // tailwind.config.js theme: { extend: { colors: { background: 'hsl(var(--background))', primary: 'hsl(var(--primary))', } } } ``

This dual-layer approach means one CSS variable change propagates to both shadcn/ui internals and your Tailwind utilities simultaneously.

packages/design-tokens/src/tokens.ts Β· TYPESCRIPT
12345678910111213141516171819202122
// @thecodeforge/design-tokens β€” centralized token definitions
// Single source of truth that generates both CSS and Tailwind config

export const designTokens = {
  colors: {
    background: { light: '0 0% 100%', dark: '222.2 84% 4.9%' },
    foreground: { light: '222.2 84% 4.9%', dark: '210 40% 98%' },
    primary: { light: '222.2 47.4% 11.2%', dark: '210 40% 98%' },
    destructive: { light: '0 84.2% 60.2%', dark: '0 62.8% 30.6%' },
  },
  radii: {
    DEFAULT: '0.5rem',
    sm: 'calc(var(--radius) - 4px)',
    md: 'calc(var(--radius) - 2px)',
    lg: 'var(--radius)',
  },
} as const;

// Build script generates:
// 1. CSS custom properties for globals.css
// 2. @theme block for Tailwind v4
// 3. TypeScript types for autocomplete
⚠ Token Synchronization Risk
πŸ“Š Production Insight
Token drift is the number one cause of visual inconsistency in scaled design systems.
Build a token generation script that outputs CSS from a single TypeScript source β€” never hand-edit HSL values in two places.
Run this in CI: parse tokens.ts and globals.css, fail build if values diverge.
🎯 Key Takeaway
Tokens are the atomic layer β€” get them wrong and every component inherits the error.
Synchronize CSS custom properties and Tailwind config from a single source of truth.
One variable change must propagate to both shadcn/ui internals and your utility classes simultaneously.

Extending shadcn/ui Components for Your Design System

Raw shadcn/ui components are starting points, not finished products. A real design system requires variants, compound components, and design-system-specific APIs that match your team's mental model.

The pattern for extending components:

  1. Keep the Radix primitive as the foundation
  2. Add variant support using class-variance-authority (cva)
  3. Expose a clean API that hides implementation details
  4. Add 'use client' directive for Next.js App Router compatibility

The key insight: your design system components should communicate intent, not implementation. A <Button variant="destructive"> tells the developer what the button means. A <Button className="bg-red-500"> tells them what color it is. Your API should enforce the former.

src/components/design-system/button.tsx Β· TYPESCRIPT
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
'use client';

// @thecodeforge/design-system β€” Extended Button with semantic variants
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';

const buttonVariants = cva(
  'inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
  {
    variants: {
      variant: {
        primary: 'bg-primary text-primary-foreground hover:bg-primary/90',
        secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
        destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
        outline: 'border border-input bg-background hover:bg-accent hover:text-accent-foreground',
        ghost: 'hover:bg-accent hover:text-accent-foreground',
        link: 'text-primary underline-offset-4 hover:underline',
      },
      size: {
        sm: 'h-9 rounded-md px-3',
        md: 'h-10 px-4 py-2',
        lg: 'h-11 rounded-md px-8',
        icon: 'h-10 w-10',
      },
    },
    defaultVariants: {
      variant: 'primary', // Note: shadcn default is 'default' β€” we use semantic 'primary'
      size: 'md',
    },
  }
);

export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
  asChild?: boolean;
  loading?: boolean;
  leftIcon?: React.ReactNode;
  rightIcon?: React.ReactNode;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, loading = false, leftIcon, rightIcon, children, disabled, ...props }, ref) => {
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} disabled={disabled || loading} {...props}>
        {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
        {!loading && leftIcon && <span className="mr-2">{leftIcon}</span>}
        {children}
        {!loading && rightIcon && <span className="ml-2">{rightIcon}</span>}
      </Comp>
    );
  }
);
Button.displayName = 'Button';
export { Button, buttonVariants };
Mental Model
Component API Design Philosophy
Your component API should communicate design intent, not CSS implementation details.
  • variant="destructive" communicates meaning β€” the developer knows what it does
  • className="bg-red-500" communicates appearance β€” the developer must infer intent
  • Good APIs make correct usage easy and incorrect usage impossible
  • cva maps semantic variants to Tailwind classes β€” that indirection is your consistency layer
πŸ“Š Production Insight
Teams that skip the extension layer end up with hundreds of one-off className overrides.
Every override is a future maintenance burden β€” it bypasses your design system's consistency guarantees.
Invest in variant APIs upfront; the cost of adding a variant is trivial compared to debugging 50 inconsistent implementations.
🎯 Key Takeaway
Extensions should communicate design intent through semantic variants.
Never expose raw Tailwind classes as the primary customization API.
cva maps intent to implementation β€” that indirection is your design system's consistency layer.
When to Extend vs When to Create New
Ifshadcn/ui component matches 80%+ of requirements
β†’
UseExtend with additional variants and props β€” keep the Radix primitive
IfComponent requires fundamentally different behavior
β†’
UseCreate a new component using Radix Primitives directly
IfOnly styling differs, behavior is identical
β†’
UseAdd a variant to the existing component via cva
IfComponent combines multiple primitives (e.g., combobox + popover)
β†’
UseCreate a compound component that composes Radix primitives internally

Accessibility: What Radix Gives You and What You Must Maintain

Radix Primitives handle the hardest accessibility problems: focus trapping, keyboard navigation, ARIA attribute management, and screen reader announcements. This is why shadcn/ui builds on Radix β€” the accessibility foundation is production-grade.

But accessibility is not a feature you install once. It degrades through customization. Common failure modes:

  1. Overriding focus styles β€” removing focus-visible:ring-2 because it looks ugly, then keyboard users lose focus indicators
  2. Breaking semantic HTML β€” wrapping a button's content in a div that breaks screen reader traversal
  3. Ignoring color contrast β€” customizing tokens without verifying WCAG AA ratios
  4. Dismissing portal behavior β€” moving Dialog.Content outside Dialog.Portal to fix a z-index issue, breaking focus management

Your design system must enforce accessibility as a constraint, not a suggestion. Build accessibility checks into your component development workflow.

src/components/design-system/accessible-form-field.tsx Β· TYPESCRIPT
1234567891011121314151617181920212223242526272829303132333435363738
'use client';

import * as React from 'react';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';

interface FormFieldProps {
  label: string;
  htmlFor: string;
  error?: string;
  hint?: string;
  required?: boolean;
  children: React.ReactElement;
  className?: string;
}

export function AccessibleFormField({ label, htmlFor, error, hint, required, children, className }: FormFieldProps) {
  const hintId = hint ? `${htmlFor}-hint` : undefined;
  const errorId = error ? `${htmlFor}-error` : undefined;
  const describedBy = [hintId, errorId].filter(Boolean).join(' ') || undefined;

  return (
    <div className={cn('space-y-2', className)}>
      <Label htmlFor={htmlFor}>
        {label}
        {required && <span className="text-destructive ml-1" aria-hidden="true">*</span>}
      </Label>
      {hint && <p id={hintId} className="text-sm text-muted-foreground">{hint}</p>}
      {React.cloneElement(children, {
        id: htmlFor,
        'aria-describedby': describedBy,
        'aria-invalid': error ? true : undefined,
        'aria-required': required || undefined,
      })}
      {error && <p id={errorId} className="text-sm text-destructive" role="alert">{error}</p>}
    </div>
  );
}
⚠ Accessibility Regression Risk
πŸ“Š Production Insight
Accessibility regressions are silent β€” they do not appear in functional tests or visual diffs.
axe-core catches roughly 57% of WCAG violations per Deque research; the remaining 43% require manual testing.
Schedule quarterly keyboard-only navigation audits across all product surfaces.
🎯 Key Takeaway
Radix handles accessibility primitives β€” your job is to not break them.
Every customization that touches focus, ARIA, or semantic HTML is a potential regression.
Automated tools catch ~57%; manual keyboard testing catches the rest.

Theming: Light, Dark, and Beyond

shadcn/ui ships with a CSS-variable-based theming system that supports light and dark modes out of the box. But production design systems need more: brand themes, high-contrast modes, or customer-specific overrides.

The architecture that scales:

  1. Define all color values as CSS custom properties
  2. Use hsl(var(--token)) or @theme variables so utilities resolve correctly
  3. Toggle themes by changing a class on the root element
  4. Critical: Apply theme before first paint to prevent FOUC

For Next.js App Router, add a blocking script in your root layout:

app/layout.tsx Β· TYPESCRIPT
123456789101112131415161718192021222324
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <script
          dangerouslySetInnerHTML={{
            __html: `
              try {
                const theme = localStorage.getItem('theme') || 'system';
                const resolved = theme === 'system' 
                  ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
                  : theme;
                document.documentElement.classList.add(resolved);
              } catch {}
            `,
          }}
        />
      </head>
      <body>
        <ThemeProvider>{children}</ThemeProvider>
      </body>
    </html>
  );
}
πŸ’‘Theme Architecture Tip
  • Store theme preference in localStorage for persistence
  • Always resolve 'system' to 'light' or 'dark' before applying classes
  • Use next-themes package β€” it implements this pattern correctly for RSC
  • Blocking script adds ~1ms to first paint but eliminates FOUC completely
πŸ“Š Production Insight
Theme switching causes FOUC when script runs after paint. The blocking script in <head> reads localStorage and sets the theme class before React hydrates β€” eliminating flash entirely.
This is why we recommend next-themes instead of custom providers; it handles RSC, system preference, and FOUC prevention out of the box.
🎯 Key Takeaway
Theming must resolve before first paint to avoid FOUC.
Use a blocking <head> script or next-themes package.
Never hardcode colors in components β€” always reference tokens that theming can override.

Component Documentation and Governance

A design system without documentation is a component graveyard. Teams will not use components they cannot discover, understand, or trust.

Documentation for a shadcn/ui-based design system should cover:

  1. Component API β€” props, variants, slots, and their intended usage
  2. Design rationale β€” why this component exists and when to use it
  3. Accessibility notes β€” what Radix handles automatically and what consumers must maintain
  4. Composition patterns β€” how to combine components for common workflows
  5. Anti-patterns β€” what not to do and why

Storybook is the standard tool for component documentation. It provides isolated rendering, interactive prop controls, and accessibility auditing via the a11y addon. But Storybook alone is not governance β€” you need lint rules that enforce design system usage.

.eslintrc.js Β· JAVASCRIPT
123456789101112131415161718192021
// Enforce design system usage
module.exports = {
  plugins: ['tailwindcss'],
  rules: {
    // Prevent direct imports from raw shadcn/ui β€” use design system wrappers
    'no-restricted-imports': [
      'error',
      {
        patterns: [{
          group: ['@/components/ui/*'],
          message: 'Import from @/components/design-system/* instead of raw ui components.',
        }],
      },
    ],
    // Enforce design tokens (requires eslint-plugin-tailwindcss)
    'tailwindcss/no-custom-classname': ['warn', {
      whitelist: ['bg-background', 'text-foreground', 'bg-primary', 'bg-destructive']
    }],
    'tailwindcss/enforces-shorthand': 'error',
  },
};
πŸ”₯Governance Beyond Documentation
Documentation tells teams what to do. Lint rules prevent them from doing the wrong thing. Both are necessary β€” documentation without enforcement leads to drift, enforcement without documentation leads to frustration.
πŸ“Š Production Insight
Component documentation decays faster than component code β€” assign documentation ownership explicitly.
Storybook stories should include a11y addon results so accessibility violations surface during development.
Lint rules that block raw ui imports force teams through your design system's API surface.
🎯 Key Takeaway
Documentation without enforcement leads to drift β€” enforce with lint rules.
Storybook provides isolation and interactivity β€” use it for component discovery and testing.
Assign documentation ownership explicitly β€” it decays faster than code without a maintainer.
Documentation Strategy by Team Size
IfSolo developer or team of 2–3
β†’
UseJSDoc comments and a README β€” Storybook adds overhead you cannot maintain
IfTeam of 4–10 with shared components
β†’
UseStorybook with a11y addon and basic prop documentation
IfMultiple teams consuming a shared design system
β†’
UseFull Storybook + design system site with governance docs, migration guides, and changelog
πŸ—‚ Component Library Architecture Comparison
How shadcn/ui compares to traditional approaches
Aspectshadcn/ui + RadixMaterial UI / MUICustom Radix Primitives
Source ownershipYou own the codenpm dependencyYou own the code
AccessibilityRadix handles primitivesBuilt-in, opinionatedYou implement everything
Styling approachTailwind utilitiesEmotion / styled-componentsYour choice
Customization depthUnlimited β€” source accessTheme API + overridesUnlimited β€” from scratch
Maintenance burdenMedium β€” merge upstream changesLow β€” update packageHigh β€” build everything
Bundle size controlFull β€” import only what you usePartial β€” tree-shaking helpsFull β€” minimal by default
Learning curveModerate β€” Radix + TailwindLow β€” comprehensive docsHigh β€” deep Radix knowledge
RSC CompatibleYes β€” with 'use client'PartialYes β€” with 'use client'

🎯 Key Takeaways

  • shadcn/ui gives you source ownership β€” treat it as a codebase to maintain, not a package to consume
  • Token synchronization between CSS variables and Tailwind is non-negotiable β€” automate with a build script
  • Radix handles accessibility primitives β€” your job is to not break them through customization
  • Enforce design system usage with lint rules (eslint-plugin-tailwindcss), not just documentation
  • Run npx shadcn@latest diff in CI to catch upstream changes before they cause surprises
  • Always use 'use client' directive and blocking theme script for Next.js App Router

⚠ Common Mistakes to Avoid

    βœ•Treating shadcn/ui as a black-box dependency
    Symptom

    Developers avoid modifying component source, creating wrapper components with className overrides instead.

    Fix

    Embrace the ownership model β€” modify component source directly. The code is in your project for a reason.

    βœ•Skipping token synchronization between CSS variables and Tailwind
    Symptom

    Components render with slightly different colors depending on whether they use Tailwind classes or CSS variables directly.

    Fix

    Build a token generation script (tokens.ts β†’ globals.css) that outputs both from a single source. Run in CI.

    βœ•Overriding Radix accessibility behavior without understanding consequence
    Symptom

    Keyboard navigation breaks, focus traps stop working, or screen readers announce incorrect information after customization.

    Fix

    Read the Radix documentation for each primitive before overriding any behavior. Test with keyboard-only navigation after every change.

    βœ•Using arbitrary Tailwind colors instead of design system tokens
    Symptom

    Components use bg-red-500 or text-blue-600 instead of bg-destructive or text-primary, bypassing theming.

    Fix

    Add eslint-plugin-tailwindcss with no-custom-classname rule. All colors must reference design system tokens.

    βœ•Not running diff before updating
    Symptom

    Upstream changes introduce breaking API changes that silently break customizations.

    Fix

    Run npx shadcn@latest diff button in CI. Review every change before merging. Treat as dependency upgrade.

    βœ•Forgetting 'use client' in Next.js App Router
    Symptom

    Radix components throw 'Event handlers cannot be passed to Client Component' errors.

    Fix

    Add 'use client' directive to top of every design system component that uses Radix primitives or interactivity.

Interview Questions on This Topic

  • QHow does shadcn/ui's component distribution model differ from traditional component libraries like Material UI?Mid-levelReveal
    shadcn/ui copies component source code directly into your project via npx shadcn@latest add, giving you full ownership of every line. Traditional libraries ship as npm packages that you import and configure through a theme API. The shadcn/ui model means you can modify any component without fighting abstraction layers, but you take on the responsibility of merging upstream changes manually via npx shadcn@latest diff. Traditional libraries offer lower maintenance burden but limited customization depth.
  • QWhy must CSS custom properties and Tailwind config stay synchronized in a shadcn/ui design system?Mid-levelReveal
    shadcn/ui components internally reference CSS custom properties using syntax like hsl(var(--primary)), while custom components use Tailwind utility classes like bg-primary. Both resolve to the same underlying value only if the CSS variable definitions and Tailwind theme (via @theme in v4 or extend.colors in v3) reference identical values. A mismatch produces visual inconsistencies where shadcn/ui primitives and custom components render different colors despite using the same semantic token name.
  • QWhat accessibility responsibilities does Radix handle automatically, and what must developers maintain when customizing shadcn/ui components?SeniorReveal
    Radix handles focus trapping in modals and dialogs, keyboard navigation patterns (arrow keys in menus, Escape to close), ARIA attribute management (aria-expanded, aria-selected, role assignments), and screen reader announcements for state changes. Developers must maintain: visible focus indicators (do not remove focus-visible styles), semantic HTML structure (do not break label-input associations), color contrast ratios when customizing tokens (WCAG AA minimum 4.5:1), and portal behavior for overlay components (do not move content outside Dialog.Portal).
  • QHow would you enforce design system token usage across a large engineering organization?SeniorReveal
    Multi-layer enforcement: (1) ESLint rules with eslint-plugin-tailwindcss that ban arbitrary color classes like bg-red-500, requiring design system tokens like bg-destructive instead. (2) Import restrictions that prevent direct imports from @/components/ui/*, forcing teams to use design system wrapper components. (3) CI checks that parse tokens.ts and globals.css to detect token drift. (4) Visual regression testing with Chromatic that catches pixel-level inconsistencies. (5) Documentation that explains the 'why' behind token choices.
  • QWhat is the purpose of class-variance-authority (cva) in a shadcn/ui design system?Mid-levelReveal
    cva maps semantic variant names to Tailwind class strings. It provides a type-safe API where developers specify intent (variant='destructive') rather than implementation (className='bg-red-500 text-white'). This indirection layer is the design system's consistency mechanism β€” it ensures all destructive actions use the same visual treatment regardless of which developer implemented the component. cva also handles compound variants and default values, reducing boilerplate in component definitions.

Frequently Asked Questions

Can I use shadcn/ui with Vue or Svelte?

shadcn/ui is React-only because it wraps Radix Primitives which are React components. However, community ports exist: shadcn-svelte for Svelte, shadcn-vue for Vue. The core architectural pattern β€” copying source code into your project β€” applies to any framework via Ark UI primitives.

How do I handle shadcn/ui updates when I have customized components?

Run npx shadcn@latest diff button to see what changed upstream. This shows a git-style diff of every component. Review each change and decide whether to merge. Since you own the source code, you control the merge β€” there is no forced upgrade. Maintain a changelog of your customizations so you can resolve conflicts intelligently.

Should I re-export shadcn/ui components or modify them in place?

For a design system, modify in place. Re-exporting adds an abstraction layer that obscures the component's actual implementation and makes debugging harder. The shadcn/ui model assumes you will modify the source β€” that is why it copies the code into your project. If you need to add variants or props, modify the component file directly.

How do I test shadcn/ui components in my design system?

Use three testing layers: (1) Unit tests with React Testing Library for component logic and prop handling. (2) Visual regression tests with Chromatic or Percy to catch unintended style changes. (3) Accessibility tests with axe-core integrated into your test runner. Storybook provides a natural home for all three β€” write stories that serve as both documentation and test cases.

What is the performance impact of using CSS custom properties for theming?

Negligible in practice. CSS custom property resolution happens during style computation, which is a fraction of a millisecond per element. The alternative β€” generating separate CSS bundles per theme β€” adds build complexity without meaningful performance gains. For most applications, the CSS custom property approach adds less than 1ms to total page render time.

Does this work with Tailwind CSS v4?

Yes, but the configuration changes. Tailwind v4 uses CSS-first configuration with @theme directives instead of tailwind.config.js. shadcn/ui components still work because they reference CSS variables. Update your globals.css to use @theme { --color-primary: ... } and @source directives instead of content paths. The token architecture remains the same β€” just the Tailwind configuration surface changes.

πŸ”₯
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousNext.js 16 Caching Strategies Explained: The 2026 GuideNext β†’v0 + shadcn/ui: Build 5 Production Components (With Full Code)
Forged with πŸ”₯ at TheCodeForge.io β€” Where Developers Are Forged