Course contentsShow
← React
Lesson 1940 of 2,39644. Styling ApproachesFree lesson

Dynamic Runtime Styles with Recipes

Combining build-time extraction with runtime variant selection for conditional styling without inline styles.

Dynamic Runtime Styles with Recipes

What you'll learn: How to use vanilla-extract recipes to combine compile-time CSS extraction with runtime variant selection for performant conditional styling.

The Problem with Pure Runtime Styles

You've seen how vanilla-extract generates CSS at build time, giving you zero-runtime overhead. But what happens when you need styles that change based on component props? Inline styles work but sacrifice performance and capabilities. Recipes solve this elegantly.

How Recipes Work

A recipe is vanilla-extract's answer to runtime style variants. You define all possible style combinations at build time—vanilla-extract extracts them to static CSS. At runtime, your component simply applies the correct pre-generated class name based on props.

Think of it like a restaurant menu: the kitchen prepares all recipes in advance (build time), but the waiter selects which dish to serve based on the customer's order (runtime).

// button.css.ts
import { recipe } from '@vanilla-extract/recipes';

export const button = recipe({
  base: {
    padding: '8px 16px',
    borderRadius: '4px',
  },
  variants: {
    color: {
      primary: { background: 'blue' },
      secondary: { background: 'gray' },
    },
    size: {
      small: { fontSize: '12px' },
      large: { fontSize: '18px' },
    },
  },
  defaultVariants: {
    color: 'primary',
    size: 'small',
  },
});
// Button.tsx
import { button } from './button.css';

export function Button({ color, size, children }) {
  return (
    <button className={button({ color, size })}>
      {children}
    </button>
  );
}

The button() function is type-safe and returns the appropriate class name string. No runtime style generation—just class name selection.

Key Takeaway: Recipes let you write prop-driven conditional styles that feel dynamic but are actually pre-generated static CSS, giving you both developer ergonomics and optimal performance.