The theme switches before React hydrates so nobody sees a flash
The site has a dark mode and a light mode. The toggle is a button fixed in the top-right corner of every page. When you click it, it does three things — sets a data-theme attribute on the document element, saves the value to localStorage, and updates local state. That last one re-renders the button so the icon swaps from a sun to a moon. The interesting part is what happens before any of that. The root layout has a six-line inline script in the head element, rendered with dangerouslySetInnerHTML. It reads localStorage synchronously and sets the data-theme attribute on the html element before the browser paints a single pixel. The script runs during HTML parsing, before React hydrates, before any component mounts. If you chose light mode yesterday, the page opens in light mode today with zero flash. No white-to-dark flicker, no layout shift, no FOUC. The script is one hundred and three characters. It costs nothing. The reactivity system is equally minimal. Every component that needs to know the current theme calls the useTheme hook. The hook does not use a context provider. It does not use an event listener. It sets up a MutationObserver that watches the data-theme attribute on the document element. When ThemeToggle flips the attribute, the observer fires, the hook updates its state, and the component re-renders with the new theme. No prop drilling, no context wrapper, no event bus. One DOM attribute is the single source of truth. The MutationObserver disconnects on unmount. The CSS layer handles the rest — the root selector defines dark mode custom properties, the data-theme light selector overrides them. Every Tailwind class, every accent colour, every glass surface reads from those properties. One attribute drives the entire visual system. The ThemeToggle button itself is forty-four pixels square with a glass background and the accent border on hover. It meets the WCAG minimum touch target. The aria-label updates dynamically — Switch to light mode when you are in dark, Switch to dark mode when you are in light. One button, one script, one observer, zero context providers.
Comments coming soon
Sign in with TikTok to leave a comment. Coming soon.