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

Server-Side Rendering with CSS-in-JS

Extracting critical CSS on the server: ServerStyleSheet (styled-components) or extractCritical (Emotion) for SSR hydration.

Server-Side Rendering with CSS-in-JS

You'll learn how to extract critical CSS on the server so your styled components hydrate correctly in SSR environments.

When you render React components on the server (SSR), styled-components and Emotion don't automatically know which styles to include in the initial HTML. Without special handling, your app would render unstyled on first load, then suddenly "flash" into styled once JavaScript hydrates—a jarring user experience.

The Problem

CSS-in-JS libraries generate styles dynamically as components render. On the client, they inject these styles into the DOM immediately. But on the server, there's no DOM—just an HTML string being built. You need to collect all the styles generated during SSR and embed them in the HTML <head> so the browser applies them before hydration.

The Solutions

styled-components provides ServerStyleSheet:

import { ServerStyleSheet } from 'styled-components';

// On your server (e.g., Express route):
const sheet = new ServerStyleSheet();
const html = renderToString(sheet.collectStyles(<App />));
const styleTags = sheet.getStyleTags(); // Extract CSS
sheet.seal(); // Clean up

// Inject styleTags into <head> of your HTML template

Emotion offers extractCritical:

import { renderToString } from 'react-dom/server';
import { extractCritical } from '@emotion/server';

const { html, css, ids } = extractCritical(renderToString(<App />));

// Inject css into <style> tag in your HTML

Both APIs wrap your server render, capture generated styles, and return them as strings you embed in your HTML template. This ensures styles arrive with the HTML, preventing the unstyled flash.

Key Takeaway: Use ServerStyleSheet (styled-components) or extractCritical (Emotion) to collect and inject critical CSS during server-side rendering, ensuring styled content arrives with your initial HTML payload.