JavaScript and React course ยท Module 14: Advanced Styling

Zero-runtime CSS-in-JS - Cosmic Style Compilation

4 min read ยท
In this lesson8

Pilot, imagine two types of spaceship engines. The first calculates the flight trajectory in flight -- consuming fuel on the go (runtime CSS-in-JS like styled-components). The second calculates the trajectory before launch and saves it in the onboard computer -- during flight it doesn't consume any extra energy (zero-runtime CSS-in-JS). In the frontend world, this is the difference between runtime and zero-runtime approaches to styling.

The problem with runtime CSS-in-JS

Styled-components and Emotion work like this: every time React renders a component, the library at runtime parses the template literal, generates a unique class hash, and injects a <style> tag into the DOM. This means:

// Styled-components -- runtime
const Card = styled.div`
  background: ${({ theme }) => theme.colors.surface};
  padding: ${({ theme }) => theme.spacing.lg};
  border-radius: 12px;
`;
// On every render: parse template -> generate hash -> inject <style>

Problems:

  • Larger bundle -- the library (~12-15 KB gzip) must be loaded
  • Slower rendering -- generating styles at runtime costs time
  • SSR complications -- styles must be extracted and injected into HTML

What is zero-runtime CSS-in-JS?

Zero-runtime CSS-in-JS is an approach where styles are generated at compile time (build time) -- the resulting code contains no JavaScript for handling styles. You write styles in TypeScript, and the bundler converts them into a plain CSS file.

Vanilla-extract -- TypeScript-first styling

Vanilla-extract is the most popular zero-runtime library. You define styles in .css.ts files:

// styles.css.ts -- styles file
import { style } from '@vanilla-extract/css';

export const card = style({
  background: '#1a1a4e',
  border: '2px solid #3949ab',
  borderRadius: '12px',
  padding: '20px',
  transition: 'all 0.3s ease',
  ':hover': {
    borderColor: '#7c4dff',
    transform: 'translateY(-2px)',
  },
});

export const heading = style({
  color: '#7c4dff',
  fontSize: '20px',
  marginBottom: '16px',
});

In the React component, you import classes as plain strings:

// Component.tsx
import { card, heading } from './styles.css.ts';

function MissionCard({ title, children }) {
  return (
    <div className={card}>
      <h3 className={heading}>{title}</h3>
      {children}
    </div>
  );
}

After compilation, card and heading are just strings with CSS class names -- zero JavaScript at runtime.

Sprinkles -- typed utility classes

Vanilla-extract offers sprinkles -- a typed equivalent of utility classes (like Tailwind, but with full TypeScript typing):

// sprinkles.css.ts
import { defineProperties, createSprinkles } from '@vanilla-extract/sprinkles';

const responsiveProperties = defineProperties({
  conditions: {
    mobile: {},
    tablet: { '@media': 'screen and (min-width: 768px)' },
    desktop: { '@media': 'screen and (min-width: 1024px)' },
  },
  defaultCondition: 'mobile',
  properties: {
    display: ['none', 'flex', 'block', 'grid'],
    padding: { sm: '8px', md: '16px', lg: '24px' },
    gap: { sm: '8px', md: '16px', lg: '24px' },
  },
});

export const sprinkles = createSprinkles(responsiveProperties);

Usage:

<div className={sprinkles({
  display: { mobile: 'block', tablet: 'grid' },
  padding: { mobile: 'sm', desktop: 'lg' },
  gap: 'md',
})}>

Everything is typed -- TypeScript will suggest available values and catch typos.

Linaria -- zero-runtime with styled-components syntax

Linaria offers syntax identical to styled-components but compiles styles at build time:

import { styled } from '@linaria/react';

const Card = styled.div`
  background: #1a1a4e;
  border: 2px solid #3949ab;
  border-radius: 12px;
  padding: 20px;
  &:hover {
    border-color: #7c4dff;
  }
`;

It looks identical to styled-components, but after compilation Card renders <div className="hash123"> -- with no runtime JS.

Panda CSS -- a modern alternative

Panda CSS is the newest player -- it combines the utility-first approach (like Tailwind) with typing and zero-runtime:

import { css } from '../styled-system/css';

function MissionPanel() {
  return (
    <div className={css({
      bg: 'surface',
      p: '6',
      borderRadius: 'lg',
      border: '2px solid',
      borderColor: 'border',
      _hover: { borderColor: 'primary' },
    })}>
      Mission Panel
    </div>
  );
}

Panda generates atomic CSS (like Tailwind) at build time -- each property is a separate class, which minimizes duplication.

Comparison: runtime vs zero-runtime

Featurestyled-componentsVanilla-extractLinariaPanda CSS
Runtime JSYes (~12 KB)NoNoNo
Dynamic stylesFull (props)Limited (recipes)LimitedLimited
TypeScriptGoodNativeGoodNative
SSRConfiguration neededSeamlessSeamlessSeamless
DX (experience)GreatGoodGreatGreat

When to choose zero-runtime?

  • Large applications -- every kilobyte of runtime counts
  • SSR (Next.js, Remix) -- no problems with style hydration
  • TypeScript-first -- full typing of CSS values
  • Performance -- no runtime cost = faster rendering
Code for this lesson: App.jsx
import React, { useState } from 'react';
import './styles.css';

// Comparison: runtime vs zero-runtime CSS-in-JS
// In Sandpack we can't use vanilla-extract/Linaria/Panda,
// so we demonstrate the comparison concept

function CodeBlock({ title, code, language }) {
  return (
    <div className="code-block">
      <div className="code-header">
        <span className="code-lang">{language}</span>
        <span className="code-title">{title}</span>
      </div>
      <pre className="code-content">{code}</pre>
    </div>
  );
}

function ApproachCard({ name, desc, runtime, bundle, typescript, ssr, active, onClick }) {
  return (
    <div className={`approach-card ${active ? 'approach-active' : ''}`} onClick={onClick}>
      <h3 className="approach-name">{name}</h3>
      <p className="approach-desc">{desc}</p>
      <div className="approach-badges">
        <span className={`badge ${runtime === 'Zero' ? 'badge-green' : 'badge-red'}`}>
          Runtime: {runtime}
        </span>
        <span className={`badge ${bundle === 'Minimal' ? 'badge-green' : 'badge-yellow'}`}>
          Bundle: {bundle}
        </span>
        <span className={`badge ${typescript === 'Native' ? 'badge-green' : 'badge-blue'}`}>
          TS: {typescript}
        </span>
        <span className={`badge ${ssr === 'Seamless' ? 'badge-green' : 'badge-yellow'}`}>
          SSR: {ssr}
        </span>
      </div>
    </div>
  );
}

const approaches = [
  {
    name: 'Vanilla-extract',
    desc: 'TypeScript-first, zero-runtime. Styles in .css.ts files',
    runtime: 'Zero', bundle: 'Minimal', typescript: 'Native', ssr: 'Seamless',
    code: `// styles.css.ts
import { style } from '@vanilla-extract/css';

export const card = style({
  background: '#1a1a4e',
  border: '2px solid #3949ab',
  borderRadius: '12px',
  padding: '20px',
  ':hover': {
    borderColor: '#7c4dff',
  },
});

// Component.tsx
import { card } from './styles.css.ts';
<div className={card}>Mission panel</div>`,
  },
  {
    name: 'Linaria',
    desc: 'Styled-components syntax, but zero-runtime',
    runtime: 'Zero', bundle: 'Minimal', typescript: 'Good', ssr: 'Seamless',
    code: `import { styled } from '@linaria/react';

const Card = styled.div\`
  background: #1a1a4e;
  border: 2px solid #3949ab;
  border-radius: 12px;
  padding: 20px;
  &:hover {
    border-color: #7c4dff;
  }
\`;

// Looks like styled-components
// but compiles to plain CSS`,
  },
  {
    name: 'Panda CSS',
    desc: 'Utility-first + zero-runtime. A modern alternative',
    runtime: 'Zero', bundle: 'Minimal', typescript: 'Native', ssr: 'Seamless',
    code: `import { css } from '../styled-system/css';

function Panel() {
  return (
    <div className={css({
      bg: 'surface',
      p: '6',
      borderRadius: 'lg',
      border: '2px solid',
      borderColor: 'border',
      _hover: { borderColor: 'primary' },
    })}>
      Mission panel
    </div>
  );
}`,
  },
  {
    name: 'Styled-components (runtime)',
    desc: 'Full dynamic styles, but with a runtime JS cost',
    runtime: '~12KB', bundle: 'Large', typescript: 'Good', ssr: 'Configuration required',
    code: `import styled from 'styled-components';

const Card = styled.div\`
  background: \${({ theme }) => theme.colors.surface};
  border: 2px solid \${({ active }) =>
    active ? '#7c4dff' : '#3949ab'};
  border-radius: 12px;
  padding: 20px;
\`;

// Full dynamic styles with props
// but runtime JS parses the template on every render`,
  },
];

export default function App() {
  const [selected, setSelected] = useState(0);

  return (
    <div className="app">
      <h1 className="heading">Zero-runtime CSS-in-JS</h1>
      <p className="subtitle">Comparing approaches: build-time vs runtime</p>

      <div className="grid">
        {approaches.map((a, i) => (
          <ApproachCard key={a.name} {...a} active={i === selected} onClick={() => setSelected(i)} />
        ))}
      </div>

      <div className="detail-panel">
        <h2 className="detail-title">{approaches[selected].name} -- example code</h2>
        <CodeBlock
          title={approaches[selected].name}
          language={approaches[selected].name === 'Vanilla-extract' ? 'TypeScript' : 'JSX'}
          code={approaches[selected].code}
        />
      </div>
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does 'zero-runtime' mean in the context of CSS-in-JS libraries?

  2. 2. In what file format do you define styles in vanilla-extract?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Implement a styling methods comparison with conditional highlighting

  • Horizontal ordering

    Arrange the syntax for importing a style from a vanilla-extract file in a component:

  • Code editor

    Implement a CSS-in-JS comparison table with highlighting

  1. QuestionZero-runtime CSS-in-JS
  2. QuestionVanilla-extract -- File Extension
  3. Coding taskPractice: Comparing Styling Methods
  4. Put in orderImporting Styles from vanilla-extract
  5. QuestionMain Advantage of Zero-runtime CSS-in-JS
  6. Coding taskPractice: CSS-in-JS Comparison Table

Useful articles