JavaScript and React course ยท Module 14: Advanced Styling

CSS-in-JS - Advanced Navigation Systems

4 min read ยท
In this lesson5

Styled-components is not the only CSS-in-JS library. There are others, each with unique advantages. Let's explore two of the most important ones: Emotion and vanilla-extract.

Emotion

Emotion is a CSS-in-JS library that offers two ways of using it:

Object API (@emotion/react)

/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';

function SpacePanel({ isActive }) {
  return (
    <div css={css`
      background: #0d1137;
      border: 2px solid ${isActive ? '#00e676' : '#3949ab'};
      border-radius: 12px;
      padding: 20px;
      transition: border-color 0.3s ease;
    `}>
      <h2>Navigation Panel</h2>
    </div>
  );
}

Styled API (@emotion/styled)

import styled from '@emotion/styled';

const Card = styled.div`
  background: #1a1a4e;
  padding: 20px;
  border-radius: 12px;
`;

// Or object syntax:
const CardObj = styled.div({
  background: '#1a1a4e',
  padding: 20,
  borderRadius: 12,
});

Advantages of Emotion

  • Two APIs -- you can use template literals or JS objects
  • Lightweight -- smaller bundle than styled-components
  • High performance -- optimized runtime
  • css prop -- you can add styles directly via the css prop

Vanilla-extract -- Zero-runtime CSS-in-JS

Vanilla-extract is a completely different approach: styles are generated at compile time, not at runtime. Zero JavaScript in the client bundle!

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

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

export const title = style({
  color: '#7c4dff',
  fontSize: 24,
});
// Component.tsx
import { panel, title } from './styles.css.ts';

function SpacePanel() {
  return (
    <div className={panel}>
      <h2 className={title}>Panel</h2>
    </div>
  );
}

Advantages of vanilla-extract

  • Zero runtime -- no additional JS in the browser
  • TypeScript-first -- full typing, auto-completion
  • Type-safe -- compilation error when using a non-existent style
  • Theming -- built-in theme system with CSS variables

CSS-in-JS Comparison

FeatureStyled-componentsEmotionVanilla-extract
RuntimeYesYesNo (zero-runtime)
BundleLargerMediumMinimal
TypeScriptGood supportGood supportNative TS
SSRRequires configurationRequires configurationSeamless
DXVery goodVery goodRequires build

When to use which library?

The choice of CSS-in-JS library depends on several factors:

Choose styled-components when:

  • Your team already knows this library -- it's the most popular and has the largest community
  • You need a rich ecosystem of plugins and tools
  • You care about code readability -- tagged template literals are intuitive for developers who know CSS

Choose Emotion when:

  • You want flexibility -- you can use both template literals and JS objects
  • You care about a smaller bundle size
  • You use Next.js or another framework where Emotion has better integration
  • You need the css prop for quickly adding inline-like styles with the full power of CSS

Choose vanilla-extract when:

  • Performance is the number one priority -- zero JS in the client bundle
  • You use TypeScript and want full type safety
  • You're building a large application where bundle size matters
  • You don't need dynamic styles based on runtime props

Trend: zero-runtime CSS-in-JS

More and more projects are moving to zero-runtime solutions like vanilla-extract, Panda CSS, or Linaria. The reason? In large applications, runtime CSS-in-JS (styled-components, Emotion) can slow down rendering because it generates styles in JavaScript while the application is running.

Zero-runtime generates CSS classes at compile time -- it's like preparing a navigation map before launch instead of calculating the route in flight. The result: faster page loading and better Core Web Vitals scores.

// Panda CSS -- another popular zero-runtime alternative
import { css } from '../styled-system/css';

function Panel() {
  return (
    <div className={css({
      bg: 'slate.900',
      p: '4',
      rounded: 'xl',
      border: '2px solid',
      borderColor: 'indigo.700'
    })}>
      Panel content
    </div>
  );
}

Regardless of which library you choose, the key is to stick with one approach within a project and establish conventions with your team.

Code for this lesson: App.jsx
import React from 'react';
import './styles.css';

// Showcase of different CSS-in-JS: Emotion, vanilla-extract
// (In Sandpack we can't use Emotion/vanilla-extract,
//  so we demonstrate the syntax as a comparison)

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 ComparisonSection({ title, children }) {
  return (
    <div className="section">
      <h2 className="section-title">{title}</h2>
      {children}
    </div>
  );
}

export default function App() {
  return (
    <div className="app">
      <h1 className="heading">CSS-in-JS: Emotion vs Vanilla-extract</h1>
      <p className="subtitle">Advanced styling libraries</p>

      <ComparisonSection title="Emotion -- css prop">
        <CodeBlock
          title="Inline styles z css prop"
          language="JSX"
          code={`/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';

function Panel({ isActive }) {
  return (
    <div css={css\`
      background: #0d1137;
      border: 2px solid \${isActive ? '#00e676' : '#3949ab'};
      padding: 20px;
    \`}>
      Panel content
    </div>
  );
}`}
        />
        <div className="feature-list">
          <div className="feature">
            <span className="feature-icon good">+</span>
            <span>The css prop -- styles directly on the element</span>
          </div>
          <div className="feature">
            <span className="feature-icon good">+</span>
            <span>Smaller bundle than styled-components</span>
          </div>
          <div className="feature">
            <span className="feature-icon good">+</span>
            <span>Supports both object syntax and template literals</span>
          </div>
        </div>
      </ComparisonSection>

      <ComparisonSection title="Vanilla-extract -- zero runtime">
        <CodeBlock
          title="Styles generated at compile time"
          language="TypeScript"
          code={`// styles.css.ts
import { style } from '@vanilla-extract/css';

export const panel = style({
  background: '#0d1137',
  border: '2px solid #3949ab',
  padding: 20,
  ':hover': {
    borderColor: '#7c4dff',
  },
});

// Component.tsx
import { panel } from './styles.css.ts';
<div className={panel}>Panel</div>`}
        />
        <div className="feature-list">
          <div className="feature">
            <span className="feature-icon good">+</span>
            <span>Zero runtime -- no JS for styles in the bundle</span>
          </div>
          <div className="feature">
            <span className="feature-icon good">+</span>
            <span>TypeScript-first -- full typing</span>
          </div>
          <div className="feature">
            <span className="feature-icon warn">!</span>
            <span>Requires build configuration</span>
          </div>
        </div>
      </ComparisonSection>

      <div className="comparison-table">
        <h2 className="section-title">Comparison</h2>
        <table>
          <thead>
            <tr>
              <th>Feature</th>
              <th>Styled-comp.</th>
              <th>Emotion</th>
              <th>Vanilla-extract</th>
            </tr>
          </thead>
          <tbody>
            <tr><td>Runtime JS</td><td>Yes</td><td>Yes</td><td className="highlight">No</td></tr>
            <tr><td>Bundle size</td><td>Large</td><td>Medium</td><td className="highlight">Minimal</td></tr>
            <tr><td>TypeScript</td><td>Good</td><td>Good</td><td className="highlight">Native</td></tr>
            <tr><td>SSR</td><td>Configuration</td><td>Configuration</td><td className="highlight">Seamless</td></tr>
            <tr><td>DX</td><td className="highlight">Great</td><td className="highlight">Great</td><td>Good</td></tr>
          </tbody>
        </table>
      </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. Which CSS-in-JS library generates styles at compile time (zero runtime)?

  2. 2. How does Emotion with css prop differ from styled-components?

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

Hands-on tasks in the game

  • Vertical ordering

    Arrange the stages of style processing in vanilla-extract from start to finish:

  • Horizontal ordering

    Arrange the elements needed to use the css prop in Emotion:

  • Code editor

    Implement an expandable accordion with conditional clsx

  • Click in order

    Arrange the style definition syntax in vanilla-extract:

  1. QuestionZero-runtime CSS-in-JS
  2. QuestionEmotion css Prop vs styled-components
  3. QuestionRuntime JS in Styling Methods
  4. Put in orderStages of Style Processing in vanilla-extract
  5. Put in orderEmotion css Prop
  6. Coding taskPractice: Accordion with clsx
  7. Click in orderStyle Definition in vanilla-extract

Useful articles