React has no opinion about styling. className and style are passed to the DOM, and everything else is up to you. That freedom produced a decade of competing approaches: global stylesheets, BEM, CSS Modules, CSS-in-JS at runtime, CSS-in-JS at build time, utility classes. Then Server Components arrived and quietly picked winners, because some of those approaches need JavaScript running in the browser at render time and a Server Component never runs there.
This chapter goes through the options as answers to one problem (CSS is global, components aren't), builds tiny versions of CSS Modules and runtime CSS-in-JS so you can see how each works, and ends with component libraries and animation. The interview question to be ready for: "How would you style a new React app, and does your choice work with Server Components?"
The problem: CSS is global#
A stylesheet applies to the whole document. Two components that each pick a sensible class name collide, and whichever rule comes later in the cascade wins. Here a card and an alert each import their own CSS file, both with a .title class.
import "./card.css";
import "./alert.css";
function Card() {
return (
<div className="card">
<h3 className="title">The Pragmatic Programmer</h3>
<p>Andy Hunt and Dave Thomas</p>
</div>
);
}
function Alert() {
return (
<div className="alert">
<strong className="title">Heads up</strong> This book is overdue.
</div>
);
}
export default function App() {
return (
<>
<Card />
<Alert />
</>
);
}The book title is small, orange and uppercase, because alert.css was imported second and its .title wins. Swap the two imports and the alert breaks instead. Nothing in Card changed. That's the core problem every styling approach in this chapter solves in its own way: make a component's styles apply only to that component, and make it obvious which styles are used where so you can delete them safely.
People solved it with naming conventions first. BEM (.card__title, .alert__title) works, but it's discipline, not a guarantee, and it doesn't tell you when a class is no longer used anywhere.
Build it: scoped class names#
CSS Modules turns the convention into a build step: every class name in a .module.css file is rewritten to something unique to that file, and importing the file gives you a map from the names you wrote to the names that were generated. Here's the whole idea in a few lines:
// What a bundler does with Card.module.css, at build time.
function hash(s: string) {
let h = 5381;
for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i);
return (h >>> 0).toString(36).slice(0, 5);
}
function cssModule(file: string, css: string) {
const classes: Record<string, string> = {};
const scoped = css.replace(/\.([a-zA-Z_][\w-]*)/g, (_, name: string) => {
classes[name] ??= `${file}_${name}__${hash(file + name)}`;
return "." + classes[name];
});
const tag = document.createElement("style");
tag.textContent = scoped; // a real bundler writes this into a .css file instead
document.head.append(tag);
console.log(scoped);
return classes; // what `import styles from "./Card.module.css"` gives you
}
const card = cssModule("Card", `
.card { border: 1px solid #d6d3d1; border-radius: 8px; padding: 12px; margin-bottom: 12px; }
.title { font-size: 20px; color: #292524; margin: 0 0 4px; }
`);
const alert = cssModule("Alert", `
.alert { background: #f6e3d8; padding: 8px 12px; border-radius: 8px; }
.title { color: #b4532a; text-transform: uppercase; font-size: 12px; }
`);
export default function App() {
return (
<>
<div className={card.card}>
<h3 className={card.title}>The Pragmatic Programmer</h3>
<p>Andy Hunt and Dave Thomas</p>
</div>
<div className={alert.alert}>
<strong className={alert.title}>Heads up</strong> This book is overdue.
</div>
<p style={{ fontSize: 12, color: "#78716c" }}>card.title = {card.title}</p>
</>
);
}Both files still say .title, but the browser sees .Card_title__… and .Alert_title__…. They can't collide. Three properties fall out of this:
- Scoping is a compile-time rename, so there's zero runtime cost. The output is a normal
.cssfile. - Usage is explicit.
styles.titleis a JavaScript reference. If nothing references a class, tools can find it, and a typo isundefined(or a type error with typed CSS modules) instead of a silently unstyled element. - Everything else is plain CSS: media queries,
:hover, custom properties, container queries, cascade layers. You don't give anything up.
CSS Modules, for real#
Vite, Next.js, Rsbuild and Parcel all support CSS Modules with no configuration. Any file named *.module.css is treated this way:
.card {
border: 1px solid var(--line);
border-radius: 8px;
padding: 12px;
}
.title {
font-size: 1.25rem;
margin: 0;
}
.read .title {
color: var(--muted);
text-decoration: line-through;
}Because the output is a static stylesheet, CSS Modules work in Server Components unchanged: the component renders a class name string on the server, and the framework links the CSS file in the document head. Dynamic values (a user-chosen color, a progress percentage) go through CSS custom properties set inline, style={{ "--progress": "40%" }}, read in the module with var(--progress). That keeps the stylesheet static and the dynamic part tiny.
The weak spots are design consistency (nothing stops padding: 13px next to padding: 12px) and the file-hopping between component and stylesheet. Those are the two things Tailwind targets.
Tailwind CSS v4#
Tailwind gives you a large set of small, single-purpose classes (p-3, rounded-lg, text-stone-700, hover:bg-stone-100, md:grid-cols-2) and generates only the ones your source actually uses. You style in the markup:
export function BookCard({ title, read }: { title: string; read: boolean }) {
return (
<article className="rounded-lg border border-stone-300 p-3 hover:shadow-sm">
<h3 className={read ? "text-xl text-stone-400 line-through" : "text-xl text-stone-900"}>{title}</h3>
</article>
);
}Version 4 (current: 4.3) changed how you configure it: CSS-first configuration. There's no tailwind.config.js in a new project. You import Tailwind from your CSS and define design tokens as CSS variables in an @theme block; each variable creates matching utilities.
@import "tailwindcss";
@theme {
--color-clay-500: oklch(0.58 0.13 45);
--font-display: "Inter", sans-serif;
}
/* Now bg-clay-500, text-clay-500, border-clay-500 and font-display exist,
and var(--color-clay-500) works in any CSS. */In Next.js the integration is the @tailwindcss/postcss plugin instead of the Vite one; create-next-app offers to set it up for you.
How it works matters for one classic bug. Tailwind scans your source files as text for anything that looks like a class name and generates CSS for those. It never runs your code. So a class assembled at runtime doesn't exist:
// Broken: "bg-" + color + "-500" never appears in the source as a whole string.
<span className={`bg-${color}-500`} />
// Works: every full class name appears literally somewhere.
const swatch = { red: "bg-red-500", green: "bg-green-500" } as const;
<span className={swatch[color]} />The trade-offs, honestly stated:
- For: a consistent design scale by default, styles next to markup, no naming, tiny production CSS (it grows with the number of distinct utilities, not with the number of components), and a static file that works in Server Components.
- Against: long class strings, a vocabulary to learn, and conflicting classes when a parent passes
classNameto a child (p-2andp-4together: whichever comes later in the generated stylesheet wins, not in the string). Teams usually addclsxfor conditions,tailwind-mergeto resolve conflicts, andclass-variance-authority(cva) for component variants.
Runtime CSS-in-JS and why Server Components broke it#
styled-components (2016) and Emotion made a different bet: write CSS in JavaScript, next to the component, with full access to props and a theme. The scoping is the same idea as CSS Modules (hashed class names), but it happens in the browser, during render. A toy version shows the mechanism and its cost.
import { useInsertionEffect, useState } from "react";
const inserted = new Set<string>();
function hash(s: string) {
let h = 5381;
for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i);
return (h >>> 0).toString(36);
}
// Every render: build the CSS string, hash it, and make sure a rule exists.
function useCss(styles: string) {
const className = "css-" + hash(styles);
// useInsertionEffect runs before layout effects, so the rule exists before anyone measures.
useInsertionEffect(() => {
if (inserted.has(className)) return;
inserted.add(className);
const tag = document.createElement("style");
tag.textContent = `.${className} { ${styles} }`;
document.head.append(tag);
console.log("injected", className);
}, [className, styles]);
return className;
}
function Bar({ hue }: { hue: number }) {
const className = useCss(`
height: 24px; border-radius: 6px; width: 100%;
background: hsl(${hue} 55% 45%);
`);
return <div className={className} />;
}
export default function App() {
const [hue, setHue] = useState(20);
return (
<div>
<input type="range" min={0} max={360} value={hue} onChange={(e) => setHue(Number(e.target.value))} />
<Bar hue={hue} />
<p style={{ fontSize: 13, color: "#78716c" }}>Drag the slider and watch the console: one new rule per distinct value.</p>
</div>
);
}Every render serializes a CSS string and hashes it, and every new prop value injects a new rule. That's fine for a handful of components and measurable for thousands. (Real libraries recommend passing fast-changing values through CSS variables or inline styles for this reason.) But the serious problem is architectural. Look at what this approach needs:
- JavaScript in the browser at render time, to produce the CSS at all.
- Hooks, to inject at the right moment (
useInsertionEffectexists in React 18 precisely for CSS-in-JS libraries). - Context, for the theme (
ThemeProvider), and on the server, a registry that collects the styles generated during a render so they can be written into the HTML before the markup that uses them. With streaming, that means flushing styles chunk by chunk (Next.js exposesuseServerInsertedHTMLfor this).
A Server Component has none of those: no hooks, no context, and it never runs in the browser. So the classic setup only works inside Client Components, which pushes "use client" up your tree and gives back much of the benefit of Server Components.
The libraries have reacted differently. Emotion's styled components still need to be Client Components. styled-components went into maintenance mode in March 2025, then version 6.3 added native Server Components support: in RSC it emits <style> tags inline next to the elements, and ThemeProvider becomes a pass-through with no context, so themes move to CSS variables. That works, but it's a different model with its own caveats (sibling <style> tags can break :first-child selectors, for example). For new projects the ecosystem has moved to build-time approaches.
Zero-runtime CSS-in-JS#
The build-time answer keeps the authoring experience (styles in TypeScript, typed tokens, variants) but runs the "CSS-in-JS" part at build time, so what ships is a static .css file plus class name strings. Three you'll meet:
import { style } from "@vanilla-extract/css";
// The whole file runs at build time; exports become class names.
export const button = style({
padding: "6px 12px",
borderRadius: 6,
background: "var(--clay)",
":hover": { opacity: 0.9 },
});All three work in Server Components because nothing happens at runtime except looking up strings. The cost is a compiler plugin in your build and a constraint you must respect: styles have to be statically analyzable. You can choose between predefined variants at runtime, but you can't compute arbitrary CSS from props; dynamic values go through CSS variables, the same escape hatch as CSS Modules. StyleX, from Meta, emphasizes atomic output and predictable merging (the last style passed wins, always), which matters in large codebases where components accept style overrides.
React 19's own stylesheet support#
React 19 added something useful underneath all of this. A <link rel="stylesheet"> with a precedence prop can be rendered from any component, even deep in the tree. React hoists it into <head>, de-duplicates it if several components render the same one, orders stylesheets by precedence, and when it appears inside a Suspense boundary, waits for it to load before revealing that content, so you don't get a flash of unstyled content.
function Chart() {
return (
<>
<link rel="stylesheet" href="/chart.css" precedence="default" />
<div className="chart">…</div>
</>
);
}<style> tags with href and precedence get the same treatment. Frameworks use this to colocate CSS with components; you rarely write it by hand, but it explains how a component can "bring its own CSS" in an RSC world.
Component libraries: headless or styled#
Beyond styling primitives, you'll pick whether to build components like dialogs, menus, comboboxes and tooltips yourself. Don't, at least not the behavior: focus trapping, keyboard navigation, ARIA attributes and positioning are hard (see the next chapter). The real choice is headless or styled:
- Headless primitives handle behavior and accessibility and render no visual styles: Radix Primitives (now published as one
radix-uipackage), React Aria Components (Adobe), Headless UI (Tailwind Labs), Base UI. You style them with anything above. - Styled kits ship behavior and a visual design: MUI, Mantine, Chakra UI, Ant Design. Fast to start, and you'll spend effort overriding the look to match your brand.
- shadcn/ui is neither a dependency nor a kit. It's a CLI that copies component source (built on Radix primitives and Tailwind) into your repository:
npx shadcn@latest add dialogcreatescomponents/ui/dialog.tsx, which you own and edit. You get a good default design and full control, at the cost of maintaining the code yourself; upstream fixes don't arrive withnpm update.
import { Dialog as DialogPrimitive } from "radix-ui";
export function DialogContent({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="fixed inset-0 bg-black/50" />
<DialogPrimitive.Content className={`fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-lg bg-white p-6 ${className ?? ""}`} {...props} />
</DialogPrimitive.Portal>
);
}For Server Components: interactive primitives are Client Components (they use state and effects), and that's fine. A dialog was always going to need JavaScript. The page around it can stay on the server.
Animation#
Start with CSS: transitions and keyframes cover hover states, simple enter effects and most micro-interactions, run off the main thread when they animate transform and opacity, and work in Server Components. Two tools cover the rest:
- View Transitions: React 19.3's
<ViewTransition>animates between UI states (route changes, list reorders, shared elements) using the browser's View Transitions API. Covered in Activity and View Transitions. - Motion (formerly Framer Motion; the package is now
motion) for physics-based springs, gestures, layout animations and exit animations, which CSS can't do because an unmounted element is gone:
"use client";
import { AnimatePresence, motion } from "motion/react";
export function Toast({ open, message }: { open: boolean; message: string }) {
return (
<AnimatePresence>
{open && (
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: 8 }}>
{message}
</motion.div>
)}
</AnimatePresence>
);
}AnimatePresence keeps a removed child mounted long enough to play its exit animation, which is the part plain React can't do: once a component is gone from the tree, React removes its DOM. Motion components are Client Components. Respect prefers-reduced-motion either way (Motion's useReducedMotion, or a media query).
Pitfalls#
Check your understanding#
Implement scope(file, css): rewrite every class selector in css to File_name__hash (use the provided hash), return the rewritten CSS and a classes map from original to scoped names. The same class used twice in one file must map to the same name, and the same class in two files to different names. The app injects the CSS and uses the map, so when you're done the card title is dark and the alert title is clay-colored.
export function hash(s: string) {
let h = 5381;
for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i);
return (h >>> 0).toString(36).slice(0, 5);
}
export function scope(file: string, css: string): { css: string; classes: Record<string, string> } {
// TODO: rewrite .className selectors and build the map
return { css, classes: {} };
}
(window as any).scope = scope; // for the checksWhich styling approach would need the most changes to use inside Next.js Server Components?
A Tailwind v4 project has this component. status is "error" at runtime. What color is the badge, and why?
const colors = { ok: "green", error: "red" } as const;
function Badge({ status }: { status: "ok" | "error" }) {
return <span className={`rounded px-2 text-white bg-${colors[status]}-600`}>{status}</span>;
}"How would you style a new React app, and why? Assume it uses Server Components."
Interview angle
CSS is global and components aren't, so every styling approach is a way to scope styles to a component. CSS Modules rename classes per file at build time. Tailwind generates single-purpose utility classes by scanning your source, configured in CSS with @theme in v4. Runtime CSS-in-JS like Emotion generates styles in the browser during render, using hooks and context, which is why it clashes with Server Components. Zero-runtime libraries like vanilla-extract and StyleX keep styles in TypeScript but emit static CSS. With RSC, prefer build-time CSS, use CSS variables for dynamic values, and lean on headless primitives for interactive components.
What are the main ways to style React components, and their trade-offs?
Why doesn't runtime CSS-in-JS work well with Server Components?
How do CSS Modules work?
How does Tailwind decide which CSS to generate, and what bug does that cause?
Headless component library, styled kit, or shadcn/ui: how do you choose?
Recap#
- CSS is global; every approach is a way to scope styles to a component and make usage explicit.
- CSS Modules rename classes per file at build time: plain CSS, zero runtime, works in Server Components. Dynamic values go through CSS variables.
- Tailwind v4 is configured in CSS (
@import "tailwindcss"and@theme) and generates only classes it finds written out in source, so never build class names by concatenation. - Runtime CSS-in-JS generates styles in the browser during render with hooks and context, which conflicts with Server Components. Zero-runtime libraries (vanilla-extract, Panda, StyleX) keep the authoring style and emit static CSS.
- Use headless primitives (Radix, React Aria) or shadcn/ui for interactive components; animate with CSS first, then View Transitions or Motion.
Sources#
- react.dev:
<link>and<style>(stylesheet precedence), useInsertionEffect - Tailwind CSS: Installing with Vite, Theme variables, Detecting classes in source files
- Next.js: CSS Modules and global styles, CSS-in-JS
- styled-components: Advanced usage: React Server Components; maintenance announcement
- vanilla-extract, Panda CSS, StyleX
- Radix Primitives, shadcn/ui, Motion for React
- Facts checked November 24, 2026.