Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Next.js and Tooling

SSR, Emotion and the Theme Flash

Understand server-side rendering with Material UI and Emotion: how styles are collected, why hydration mismatches happen, and how to remove flashes of unstyled or wrong-colored content.

Server-side rendering (SSR) sends finished HTML to the browser, so users see content before any JavaScript runs. With a CSS-in-JS library like Emotion, the styles are created by JavaScript, so a server renderer must also collect the CSS that the rendered components used and put it in the HTML. When that step is missing or incomplete, you get three typical problems: a flash of unstyled content, a flash of the wrong color scheme, and hydration warnings. This lesson explains what happens and how to fix each one.

MUI, Emotion and Next.js are not available in the live editors here. The real code is read-only. The runnable examples are stand-ins built with React's own react-dom/server, so you can watch server and client output differ and watch styles being collected.

How Emotion works on the server

On the client, Emotion inserts <style> rules into the document as components render. On the server there is no document. Emotion's server tools do this instead:

  1. Create an Emotion cache (a registry of the inserted styles, with a key such as css or mui).
  2. Render the React tree with that cache; each component's styles are inserted into the cache.
  3. Read the collected CSS from the cache and serialize it into <style data-emotion="mui ..."> tags in the HTML.
  4. In the browser, create a cache with the same key and let it adopt the existing style tags, so the same rules are not inserted twice.

Frameworks hide those steps: AppRouterCacheProvider in the App Router, the custom _document with createEmotionCache in the Pages Router. If you write a custom server (Express, Fastify), you do it yourself:

JSX
// Real Emotion + Material UI, read-only (custom server)
import createCache from '@emotion/cache';
import createEmotionServer from '@emotion/server/create-instance';
import { renderToString } from 'react-dom/server';
import { CacheProvider } from '@emotion/react';

const cache = createCache({ key: 'css' });
const { extractCriticalToChunks, constructStyleTagsFromChunks } = createEmotionServer(cache);

const html = renderToString(
  <CacheProvider value={cache}>
    <ThemeProvider theme={theme}><App /></ThemeProvider>
  </CacheProvider>,
);
const chunks = extractCriticalToChunks(html);
const styleTags = constructStyleTagsFromChunks(chunks); // put these in <head>

Try it: a mini style collector

This stand-in imitates the process. A tiny css() function registers rules in a collector (the "cache"). We render a component to a string with renderToString, then output the HTML and the collected CSS separately, just like the real flow.

Collecting styles while rendering on the server

If the server skipped the collector, the HTML would contain class names but no rules, until the JavaScript loaded and inserted them. That moment is the flash of unstyled content (FOUC).

Hydration mismatches

Hydration is React attaching to the server's HTML. React expects the first client render to produce exactly the same markup. If it differs, React warns ("Text content did not match", "Hydration failed") and may re-render the whole tree on the client.

With MUI the usual causes are:

Cause Example Fix
Reading browser-only values during render window.innerWidth, localStorage, matchMedia Read them after mount (in an effect), or use useSyncExternalStore with a server snapshot
useMediaQuery The server cannot know the screen size Provide ssrMatchMedia from user-agent hints, or accept a one-time re-render with noSsr, or use CSS breakpoints in sx instead
Random or time-based output Math.random(), new Date() in the render Compute it in an effect or pass it as a prop from the server
Two Emotion copies or mismatched cache keys Styles injected in a different order Use one cache, and one version of @emotion/react
Color-mode specific markup mode === 'dark' ? <Moon/> : <Sun/> where mode comes from localStorage Render nothing, or a neutral placeholder, until mode is known
Invalid HTML nesting <div> inside <p> (for example Typography as p with Box inside) Use correct elements with the component prop

When you see a hydration warning, read which element differs. In React 19 the message prints a diff of the server and client trees. Often the answer is visible in the first few lines.

Try it: a mismatch and its fix

This stand-in renders a component on the "server" (renderToString) with the width unknown, then "hydrates" it by computing the client markup. The naive version reads window.innerWidth during render, so the two outputs differ. The fixed version uses useSyncExternalStore with a server snapshot, so the first client render matches the server HTML and updates afterwards.

Server HTML vs client HTML

(Inside the preview window exists even when we call renderToString, so for the naive version both outputs show the real width. In a real server the naive text would say "unknown", and React would report a mismatch with the client. The safe version always agrees with the server on the first render.)

The flash of the wrong theme

Even with styles collected, a page can paint in the wrong colors. The server does not know that this visitor chose dark mode, so it sends light HTML. After hydration the client reads localStorage and switches. For a moment the user sees a bright page. There are three fixes, from best to simplest:

  1. CSS variables plus InitColorSchemeScript: a tiny inline script in <body> runs before the first paint, reads the saved mode (or the system preference) and sets the data-mui-color-scheme attribute. The CSS variables for that scheme apply immediately. This is the recommended approach, and it needs no extra re-render. See Dark Mode and Color Schemes.
  2. Store the choice in a cookie and read it on the server (cookies() in Next.js) to render the right scheme in the first HTML. It makes the first HTML depend on the cookie, so such pages cannot be shared from a cache.
  3. Hide until ready: render nothing for mode-dependent parts until mode is known. Acceptable for small controls, not for the page background.
JSX
// Real Material UI + Next.js, read-only: do not read the mode during render
function ThemeToggle() {
  const { mode, setMode } = useColorScheme();
  if (!mode) {
    return <Skeleton variant="circular" width={40} height={40} />; // same size, no layout shift
  }
  return (
    <IconButton onClick={() => setMode(mode === 'dark' ? 'light' : 'dark')} aria-label="toggle color mode">
      {mode === 'dark' ? <LightModeIcon /> : <DarkModeIcon />}
    </IconButton>
  );
}

Cascade order with Tailwind, CSS modules and layers

Emotion injects its <style> tags at a position in <head>. If your own CSS (Tailwind utilities, CSS modules) loads before MUI, MUI wins in a tie, and your class has no effect. Two solutions:

  • CSS layers: AppRouterCacheProvider options={{ enableCssLayer: true }} wraps MUI in @layer mui. Declare the order once in your global CSS: @layer theme, base, mui, components, utilities;, so Tailwind's components and utilities layers come after mui and win.
  • injectFirst: the older approach, StyledEngineProvider injectFirst or the cache option prepend: true, puts MUI's tags first in <head>.

Test in a production build; development servers sometimes order tags differently.

Streaming and Suspense

With streaming SSR, React sends the HTML in pieces as data resolves. AppRouterCacheProvider keeps pace: it inserts the styles belonging to each streamed chunk right before that chunk (using useServerInsertedHTML). You do not do anything extra, but remember that components under a Suspense boundary that resolve later bring their styles with them, so avoid very large Suspense boundaries that delay the styles for content above the fold.

Debugging checklist

  • Styles missing in "View Source"? The cache provider is not wrapping the tree, or the key differs between server and client.
  • Warning "Prop className did not match"? Two different Emotion caches or versions, or a conditional class that depends on the browser.
  • Colors flash on reload? Add InitColorSchemeScript and use colorSchemes with CSS variables.
  • MUI overrides your Tailwind classes? Enable layers or change the injection order.
  • Layout jumps when fonts arrive? Use next/font or font-display: swap with a matching fallback font.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must server rendering with Emotion collect styles?

    Without collected styles, the first HTML has class names with no rules until JavaScript loads and inserts them, which causes a flash of unstyled content.
  2. 2. Which of these causes a hydration mismatch?

    Those values only exist in the browser, so the server markup and the first client render differ. Read them in an effect or with useSyncExternalStore and a server snapshot.
  3. 3. What is the recommended way to prevent the flash of the wrong color scheme?

    The inline script applies the saved scheme before paint and the variables change colors without a React re-render.
  4. 4. Your Tailwind classes lose to MUI styles. What helps?

    With layers, the order of @layer declarations decides which wins, so utilities can override MUI predictably.

Summary

  • Emotion generates CSS at render time; SSR must collect it into a cache and inline it, and the browser must adopt the same cache.
  • Hydration mismatches come from browser-only values, random or time values, mismatched caches and invalid HTML nesting.
  • Use useSyncExternalStore with a server snapshot, or effects, for browser-only values.
  • InitColorSchemeScript plus CSS variables removes the wrong-theme flash.
  • Use CSS layers or injection order to make your own CSS override MUI.

Next: Tooling: TypeScript, Testing and Migration