Course contentsShow
← React
Lesson 1922 of 2,39644. Styling ApproachesFree lesson

CSS-in-JS Philosophy: Colocation and Dynamic Styles

Why CSS-in-JS exists: colocating styles with components, type-safe dynamic styling, and automatic critical CSS extraction.

CSS-in-JS Philosophy: Colocation and Dynamic Styles

What you'll learn: Why developers choose CSS-in-JS libraries and what fundamental problems they solve.

The Core Philosophy

CSS-in-JS isn't just another styling approach—it's a philosophical shift. Traditional CSS lives in separate files, disconnected from your components. CSS-in-JS brings styles directly into your JavaScript, colocating them with the components they style. Think of it like keeping your recipe and ingredients on the same page instead of flipping between a cookbook and a pantry list.

Why CSS-in-JS Exists

1. True Colocation

Your styles live right next to—or even inside—the component code. When you delete a component, its styles vanish too. No orphaned CSS rules lingering in forgotten stylesheets.

2. Dynamic Styling with JavaScript

Unlike plain CSS or CSS Modules, you can use JavaScript expressions directly in your styles. Props, state, theme values—all become part of your styling logic with full type safety. No string interpolation hacks or data attributes needed.

3. Type Safety

With TypeScript, CSS-in-JS libraries can validate your style properties, catch typos, and provide autocomplete. Your theme values, color tokens, and spacing scales become typed contracts.

4. Automatic Critical CSS

CSS-in-JS libraries analyze which components render on each page and automatically extract only the CSS needed for that specific view. No manual critical CSS extraction required—it's built into the rendering process.

The Mental Model

You're not writing CSS for components anymore; you're writing CSS as components. Styles become first-class citizens in your component architecture, with the same lifecycle, scope, and testing capabilities.

Key Takeaway: CSS-in-JS trades build-time separation for runtime colocation, enabling dynamic type-safe styling and automatic optimization at the cost of JavaScript bundle size and runtime overhead.