Dark Mode & Dynamic Color Schemes
Implementing robust dark mode requires avoiding layout flash (Flash of Unstyled Content - FOUC) when reading user theme preferences on initial page load. The standard web pattern applies a .dark class to the root <html> element based on user toggles or system prefers-color-scheme media queries.
Libraries like next-themes manage theme persistence in localStorage, inject an inline anti-FOUC script into <head>, and listen for OS theme preference changes automatically.
Exercise
Add a theme toggle button using useTheme() from next-themes that cycles between light, dark, and system modes.
Check your understanding
What causes theme flash (FOUC) when implementing dark mode in SSR applications?Show answerHide answer
Answer
The server renders default light HTML, and the client JavaScript updates the theme class only after downloading and running.How does next-themes eliminate theme flash?Show answerHide answer
Answer
It injects a tiny inline blocking script into <head> that reads localStorage/system preferences before the page paints.