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:

1// Styled-components -- runtime
2const Card = styled.div`
3  background: ${({ theme }) => theme.colors.surface};
4  padding: ${({ theme }) => theme.spacing.lg};
5  border-radius: 12px;
6`;
7// 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:

1// styles.css.ts -- styles file
2import { style } from '@vanilla-extract/css';
3
4export const card = style({
5  background: '#1a1a4e',
6  border: '2px solid #3949ab',
7  borderRadius: '12px',
8  padding: '20px',
9  transition: 'all 0.3s ease',
10  ':hover': {
11    borderColor: '#7c4dff',
12    transform: 'translateY(-2px)',
13  },
14});
15
16export const heading = style({
17  color: '#7c4dff',
18  fontSize: '20px',
19  marginBottom: '16px',
20});

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

1// Component.tsx
2import { card, heading } from './styles.css.ts';
3
4function MissionCard({ title, children }) {
5  return (
6    <div className={card}>
7      <h3 className={heading}>{title}</h3>
8      {children}
9    </div>
10  );
11}

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):

1// sprinkles.css.ts
2import { defineProperties, createSprinkles } from '@vanilla-extract/sprinkles';
3
4const responsiveProperties = defineProperties({
5  conditions: {
6    mobile: {},
7    tablet: { '@media': 'screen and (min-width: 768px)' },
8    desktop: { '@media': 'screen and (min-width: 1024px)' },
9  },
10  defaultCondition: 'mobile',
11  properties: {
12    display: ['none', 'flex', 'block', 'grid'],
13    padding: { sm: '8px', md: '16px', lg: '24px' },
14    gap: { sm: '8px', md: '16px', lg: '24px' },
15  },
16});
17
18export const sprinkles = createSprinkles(responsiveProperties);

Usage:

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

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:

1import { styled } from '@linaria/react';
2
3const Card = styled.div`
4  background: #1a1a4e;
5  border: 2px solid #3949ab;
6  border-radius: 12px;
7  padding: 20px;
8  &:hover {
9    border-color: #7c4dff;
10  }
11`;

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:

1import { css } from '../styled-system/css';
2
3function MissionPanel() {
4  return (
5    <div className={css({
6      bg: 'surface',
7      p: '6',
8      borderRadius: 'lg',
9      border: '2px solid',
10      borderColor: 'border',
11      _hover: { borderColor: 'primary' },
12    })}>
13      Mission Panel
14    </div>
15  );
16}

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
1import React, { useState } from 'react';
2import './styles.css';
3
4// Comparison: runtime vs zero-runtime CSS-in-JS
5// In Sandpack we can't use vanilla-extract/Linaria/Panda,
6// so we demonstrate the comparison concept
7
8function CodeBlock({ title, code, language }) {
9  return (
10    <div className="code-block">
11      <div className="code-header">
12        <span className="code-lang">{language}</span>
13        <span className="code-title">{title}</span>
14      </div>
15      <pre className="code-content">{code}</pre>
16    </div>
17  );
18}
19
20function ApproachCard({ name, desc, runtime, bundle, typescript, ssr, active, onClick }) {
21  return (
22    <div className={`approach-card ${active ? 'approach-active' : ''}`} onClick={onClick}>
23      <h3 className="approach-name">{name}</h3>
24      <p className="approach-desc">{desc}</p>
25      <div className="approach-badges">
26        <span className={`badge ${runtime === 'Zero' ? 'badge-green' : 'badge-red'}`}>
27          Runtime: {runtime}
28        </span>
29        <span className={`badge ${bundle === 'Minimal' ? 'badge-green' : 'badge-yellow'}`}>
30          Bundle: {bundle}
31        </span>
32        <span className={`badge ${typescript === 'Native' ? 'badge-green' : 'badge-blue'}`}>
33          TS: {typescript}
34        </span>
35        <span className={`badge ${ssr === 'Seamless' ? 'badge-green' : 'badge-yellow'}`}>
36          SSR: {ssr}
37        </span>
38      </div>
39    </div>
40  );
41}
42
43const approaches = [
44  {
45    name: 'Vanilla-extract',
46    desc: 'TypeScript-first, zero-runtime. Styles in .css.ts files',
47    runtime: 'Zero', bundle: 'Minimal', typescript: 'Native', ssr: 'Seamless',
48    code: `// styles.css.ts
49import { style } from '@vanilla-extract/css';
50
51export const card = style({
52  background: '#1a1a4e',
53  border: '2px solid #3949ab',
54  borderRadius: '12px',
55  padding: '20px',
56  ':hover': {
57    borderColor: '#7c4dff',
58  },
59});
60
61// Component.tsx
62import { card } from './styles.css.ts';
63<div className={card}>Panel misji</div>`,
64  },
65  {
66    name: 'Linaria',
67    desc: 'Styled-components syntax, but zero-runtime',
68    runtime: 'Zero', bundle: 'Minimal', typescript: 'Good', ssr: 'Seamless',
69    code: `import { styled } from '@linaria/react';
70
71const Card = styled.div\`
72  background: #1a1a4e;
73  border: 2px solid #3949ab;
74  border-radius: 12px;
75  padding: 20px;
76  &:hover {
77    border-color: #7c4dff;
78  }
79\`;
80
81// Looks like styled-components
82// but compiles to plain CSS`,
83  },
84  {
85    name: 'Panda CSS',
86    desc: 'Utility-first + zero-runtime. A modern alternative',
87    runtime: 'Zero', bundle: 'Minimal', typescript: 'Native', ssr: 'Seamless',
88    code: `import { css } from '../styled-system/css';
89
90function Panel() {
91  return (
92    <div className={css({
93      bg: 'surface',
94      p: '6',
95      borderRadius: 'lg',
96      border: '2px solid',
97      borderColor: 'border',
98      _hover: { borderColor: 'primary' },
99    })}>
100      Panel misji
101    </div>
102  );
103}`,
104  },
105  {
106    name: 'Styled-components (runtime)',
107    desc: 'Full dynamic styles, but with a runtime JS cost',
108    runtime: '~12KB', bundle: 'Large', typescript: 'Good', ssr: 'Configuration required',
109    code: `import styled from 'styled-components';
110
111const Card = styled.div\`
112  background: \${({ theme }) => theme.colors.surface};
113  border: 2px solid \${({ active }) =>
114    active ? '#7c4dff' : '#3949ab'};
115  border-radius: 12px;
116  padding: 20px;
117\`;
118
119// Full dynamic styles with props
120// but runtime JS parses the template on every render`,
121  },
122];
123
124export default function App() {
125  const [selected, setSelected] = useState(0);
126
127  return (
128    <div className="app">
129      <h1 className="heading">Zero-runtime CSS-in-JS</h1>
130      <p className="subtitle">Comparing approaches: build-time vs runtime</p>
131
132      <div className="grid">
133        {approaches.map((a, i) => (
134          <ApproachCard key={a.name} {...a} active={i === selected} onClick={() => setSelected(i)} />
135        ))}
136      </div>
137
138      <div className="detail-panel">
139        <h2 className="detail-title">{approaches[selected].name} -- example code</h2>
140        <CodeBlock
141          title={approaches[selected].name}
142          language={approaches[selected].name === 'Vanilla-extract' ? 'TypeScript' : 'JSX'}
143          code={approaches[selected].code}
144        />
145      </div>
146    </div>
147  );
148}

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

Useful articles