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

CSS Variables vs CSS-in-JS for Theming

Compare performance, DX, and capabilities: why CSS variables avoid re-renders and runtime CSS generation costs.

CSS Variables vs CSS-in-JS for Theming

What you'll learn: You'll understand why CSS variables often outperform CSS-in-JS solutions for theming by avoiding re-renders and runtime style generation.

The Performance Difference

When you toggle a theme using CSS-in-JS (like styled-components or Emotion), React must:

  1. Re-render components that consume theme values
  2. Generate new CSS strings at runtime
  3. Inject updated styles into the DOM

Think of it like repainting every wall in your house when you change the lighting—expensive and slow.

CSS variables, however, work at the browser level. When you update a variable like document.documentElement.style.setProperty('--primary-color', 'blue'), the browser handles the style changes directly. No React re-renders needed. It's like flipping a light switch—instant, with no renovation required.

Runtime Costs Compared

// CSS-in-JS: generates CSS on every theme change
const Button = styled.button`
  background: ${props => props.theme.primary}; // Runtime calculation
`;

// CSS Variables: no runtime generation
const Button = () => (
  <button className="btn">Click me</button>
);
// .btn { background: var(--primary); } ← Static CSS

Developer Experience Trade-offs

CSS-in-JS wins at:

  • Type safety for theme tokens
  • Co-locating styles with components
  • Dynamic styles based on complex logic

CSS variables win at:

  • Performance (especially theme switching)
  • Simpler mental model
  • Zero JavaScript bundle cost for styling
  • Native browser DevTools support

For theming specifically, CSS variables shine because themes are typically global, change infrequently, and don't need per-component logic.

Key Takeaway: CSS variables avoid React re-renders and runtime CSS generation costs, making them faster for theming than CSS-in-JS—though CSS-in-JS offers better type safety and dynamic capabilities for component-level styles.