tezvyn:

Preventing theme flash in SSR apps

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

SSR hydration and theme timing.

OUTLINE

flash comes from server not knowing client preference; fix with a blocking inline script setting the theme before paint.

RED FLAG

setting the theme only in a useEffect after hydration.

WHAT THIS TESTS The interviewer checks your grasp of the SSR lifecycle: what the server knows, when the client hydrates, and why a late theme application flashes. This is a classic dark-mode bug.

A GOOD ANSWER COVERS Explain the root cause: the server renders HTML without access to the user's localStorage or chosen theme, so it emits a default. The browser paints that default immediately. If your only correction happens in a React useEffect, that runs after hydration, so the user sees a flash from the default theme to the correct one. The robust fix is a tiny synchronous, render-blocking inline script placed early in the document head that reads the persisted preference (or the prefers-color-scheme system setting as fallback) and sets data-theme and color-scheme on the html element before the browser paints. Because it is inline and blocking, the correct theme is in place on first paint, and React hydration then matches it.

COMMON WRONG ANSWERS Setting the theme only inside useEffect or componentDidMount, which is too late and guarantees the flash. Trying to read localStorage on the server, which does not exist there. Using an async or deferred script for the theme, which still allows a paint with the wrong theme.

LIKELY FOLLOW-UPS How do you avoid a React hydration mismatch warning? Why must the script be synchronous and inline rather than an external file? How do you handle users with no stored preference?

ONE CONCRETE EXAMPLE You inject in the head a blocking script: it reads localStorage.theme, falls back to matchMedia prefers-color-scheme dark, and sets document.documentElement.dataset.theme accordingly, before any body content paints. The server output uses CSS variables keyed off data-theme, so when the browser paints, the right colors are already applied and the later React hydration is consistent, eliminating the flash.

Read the original → notanumber.in

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.