0
Challenge · 78Architecture & State

CSS-in-JS Concepts

Ecoused in ~25% of apps

You want a Button whose color depends on a prop, with styles co-located in the same file as the component. CSS-in-JS (styled-components, Emotion) lets you write CSS in JavaScript and compute it from props — but in 2026 you also need to know its runtime cost and why it can't run in a Server Component.

Core idea. CSS-in-JS writes styles in JavaScript, scoped to a component and computed from its props; runtime libraries (styled-components, Emotion) generate class names and inject <style> tags in the browser as the app renders, while zero-runtime libraries (vanilla-extract, Panda, StyleX) extract the same styles to a static .css file at build time.
Playground, this isn't a screenshot
THE STYLED COMPONENT — styles are written in JS, computed from props
const Button = styled.button`
  background: ${(p) => p.$variant === 'ghost' ? 'transparent' : color(p.$variant)};
  padding: ${(p) => p.$size === 'sm' ? '6px 12px' : '11px 20px'};
`;
PROP — $variant
PROP — $size
GENERATED & INJECTED INTO <head> ON RENDER — class sc-1fmbnx
.sc-1fmbnx {
  background: var(--color-brand);
  color: #fff;
  border: 1px solid var(--color-brand);
  padding: 11px 20px;
  font-size: 15px;
}

Change a prop → the style function re-runs, a new class is hashed, and a fresh <style>rule is injected — in the browser, at render time.

styled-components / Emotion — work happens in the browser
  • Ships a styling engine in the JS bundle; parses + serializes CSS as the app runs.
  • Generates class names and injects <style> tags on render — a real per-render cost.
  • Reads styles via React context, so the component must be a Client Component ("use client") — it cannot run in a React Server Component.
↑ play a little first, then dig in