Skip to content
All projects

Theme Toggle Without the Flash

Dark mode that respects the system setting and never flashes the wrong theme on load.

reactcssui

The white flash before dark mode applies happens because React runs after first paint. No amount of useEffect fixes it.

The fix

A tiny synchronous script in <head>, before any stylesheet, reads localStorage and stamps a class on <html>. It blocks paint for under a millisecond and the correct theme is live from the first frame.

Three states, not two

Most implementations store a boolean and lose the system preference forever. This stores light | dark | system, where system follows prefers-color-scheme live — change your OS theme with the page open and it follows.

Server rendering

The class is stamped before hydration, so React sees markup matching what it would have rendered. No mismatch warning, no correction pass.