A boot script shorter than a tweet kills the reload flash — and the surprise is that React never owns the switch it paints with.
Applies to React 19 (use), TanStack Start 1.x, and Tailwind CSS v4. On React 18, swap use for useContext; on Tailwind v3, use darkMode: "class" instead of @custom-variant.
The Problem
Your theme toggle is clean and correct after hydration.
// src/components/theme-toggle.tsx import { useTheme } from "@/components/providers/theme-provider"; import type { Theme } from "@/components/providers/theme-provider"; const choices: Theme[] = ["light", "dark", "system"]; export function ThemeToggle() { const { theme, setTheme } = useTheme(); return ( <select aria-label="Theme" value={theme} onChange={(event) => setTheme(event.target.value as Theme)} > {choices.map((choice) => ( <option key={choice} value={choice}> {choice} </option> ))} </select> ); } The stylesheet is equally simple:
:root { --background: #ffffff; } .dark { --background: #09090b; } Now reload with "dark" saved. What the browser does:
1. Server HTML arrives with <html class="">. 2. The browser paints white, because --background is #ffffff. 3. The JS bundle downloads and React hydrates. 4. An effect reads localStorage and adds .dark to <html>. Result: white → dark, on every reload, for every dark-mode user. Three fixes come to mind, and each one moves the problem.
- Read storage during render. React state seems like the natural home for a preference.
const [theme, setTheme] = useState<Theme>( () => (localStorage.getItem("theme") as Theme) ?? "system" ); localStorage is undefined on the server, so rendering throws. In a client-only render, server HTML and first render disagree, and React patches the DOM after paint.
- Move the read into
useEffect. It stops the crash but guarantees the flash: effects run after paint.
useEffect(() => { applyTheme((localStorage.getItem("theme") as Theme) ?? "system"); }, []); - Use
useLayoutEffector hide the page until the theme is ready. It cannot run before server HTML arrives, warns during server rendering, and hiding content trades the flash for a blank frame.
useLayoutEffect(() => { document.documentElement.classList.add("dark"); }, []); You need the preference before the browser paints, and you need it inside React after hydration; a render-time read breaks the server, and an effect always arrives one paint too late.
The resolution is to put the decision in the HTML itself, as a tiny script that runs while the document is still parsing:
<script> (function () { try { var t = localStorage.getItem("theme"); if (t !== "light" && t !== "dark" && t !== "system") t = "system"; var d = matchMedia("(prefers-color-scheme: dark)").matches; var r = t === "system" ? (d ? "dark" : "light") : t; var e = document.documentElement; e.classList.add(r); e.style.colorScheme = r; } catch (e) {} })(); </script> That is the whole trick: the class is on <html> before any themed content can paint. React picks up the same choice after hydration, then stays in charge of later changes.
The Mental Model
Think of a stage lightboard with exactly two labeled sliders, LIGHT and DARK. Only one can be up.
- Identity: the board is
document.documentElement. Its class andcolorSchemedecide what the audience sees. React context holds the note — the requestedTheme— not the position of the sliders. - Update timing: a stagehand sets the board before the doors open, using the note in their pocket. That is the inline script reading storage during HTML parse. Once the show is running, the director can move the sliders through
applyTheme, and a second stagehand can call out OS changes while the note sayssystem. - Read timing: the lighting designer never reads the note; CSS reads only the board, at paint time. React reads the note at render time. When the note says
system, both readers resolve it throughmatchMedia.
Two consequences. The board and the note can briefly disagree — theme is system while the board says dark — and that is fine, because only one of them is authoritative for pixels. And if the pocket is empty or locked, the stagehand uses the default; the show still starts.
CSS reads the switches; React reads the note.
How to Use It
Install the framework, icon, and menu pieces you need, then copy these files:
pnpm add @tanstack/react-start @tanstack/react-router tailwindcss @base-ui/react lucide-react src/ ├── components/ │ ├── providers/ │ │ └── theme-provider.tsx │ ├── theme-changer.tsx │ └── ui/ │ └── theme-menu.tsx ├── routes/ │ └── __root.tsx └── styles.css Imports below use @/ for src/. Swap in whatever alias your project uses, or use relative paths.
src/styles.css — the class hook and the tokens it controls:
@import "tailwindcss"; @custom-variant dark (&:is(.dark *)); :root { --background: #ffffff; --foreground: #18181b; --surface: #f4f4f5; --secondary: #f4f4f5; --secondary-foreground: #18181b; } .dark { --background: #09090b; --foreground: #fafafa; --surface: #18181b; --secondary: #27272a; --secondary-foreground: #fafafa; } @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --color-surface: var(--surface); --color-secondary: var(--secondary); --color-secondary-foreground: var(--secondary-foreground); } body { background: var(--background); color: var(--foreground); } @custom-variant makes dark: utilities respond to the .dark class on <html> rather than only to the OS media query.
src/components/providers/theme-provider.tsx — the whole provider:
import { createContext, use, useEffect, useState } from "react"; export type Theme = "dark" | "light" | "system"; type ThemeProviderProps = { children: React.ReactNode; defaultTheme?: Theme; storageKey?: string; }; type ThemeProviderState = { theme: Theme; setTheme: (theme: Theme) => void; }; function getThemeScript(storageKey: string, defaultTheme: Theme) { const key = JSON.stringify(storageKey); const fallback = JSON.stringify(defaultTheme); return `(function(){try{var t=localStorage.getItem(${key});if(t!=='light'&&t!=='dark'&&t!=='system'){t=${fallback}}var d=matchMedia('(prefers-color-scheme: dark)').matches;var r=t==='system'?(d?'dark':'light'):t;var e=document.documentElement;e.classList.add(r);e.style.colorScheme=r}catch(e){}})();`; } const ThemeProviderContext = createContext<ThemeProviderState>({ theme: "system", setTheme: () => {}, }); function applyTheme(theme: Theme) { const root = document.documentElement; root.classList.remove("light", "dark"); const resolved = theme === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" : theme; root.classList.add(resolved); root.style.colorScheme = resolved; } export function ThemeProvider({ children, defaultTheme = "system", storageKey = "theme", }: ThemeProviderProps) { const [currentTheme, setCurrentTheme] = useState<Theme>(defaultTheme); const [mounted, setMounted] = useState(false); useEffect(() => { const stored = localStorage.getItem(storageKey); queueMicrotask(() => { setCurrentTheme( stored === "light" || stored === "dark" || stored === "system" ? stored : defaultTheme ); }); queueMicrotask(() => { setMounted(true); }); }, [defaultTheme, storageKey]); useEffect(() => { if (!mounted) return; applyTheme(currentTheme); }, [currentTheme, mounted]); useEffect(() => { if (!mounted || currentTheme !== "system") return; const media = window.matchMedia("(prefers-color-scheme: dark)"); const onChange = () => applyTheme("system"); media.addEventListener("change", onChange); return () => media.removeEventListener("change", onChange); }, [currentTheme, mounted]); const setTheme = (next: Theme) => { localStorage.setItem(storageKey, next); setCurrentTheme(next); }; return ( <ThemeProviderContext value={{ theme: currentTheme, setTheme }}> <script suppressHydrationWarning dangerouslySetInnerHTML={{ __html: getThemeScript(storageKey, defaultTheme), }} /> {children} </ThemeProviderContext> ); } export function useTheme() { const context = use(ThemeProviderContext); return context; } src/routes/__root.tsx — mount it in the document shell, before your route content:
import type { ReactNode } from "react"; import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router"; import { ThemeProvider } from "@/components/providers/theme-provider"; import appCss from "@/styles.css?url"; export const Route = createRootRoute({ head: () => ({ links: [{ rel: "stylesheet", href: appCss }], }), shellComponent: RootDocument, }); function RootDocument({ children }: { children: ReactNode }) { return ( <html lang="en"> <head> <HeadContent /> </head> <body> <ThemeProvider defaultTheme="system" storageKey="theme"> {children} </ThemeProvider> <Scripts /> </body> </html> ); } src/components/ui/theme-menu.tsx — a minimal generic stand-in for the button and menu primitives. Swap it for your own UI kit; only the exported names matter to the changer:
import { Button as ButtonPrimitive } from "@base-ui/react/button"; import { Menu } from "@base-ui/react/menu"; import type { ReactNode } from "react"; export function Button(props: ButtonPrimitive.Props) { return ( <ButtonPrimitive className="inline-flex size-9 items-center justify-center rounded-lg bg-secondary text-secondary-foreground" {...props} /> ); } export function DropdownMenu({ children }: { children: ReactNode }) { return <Menu.Root>{children}</Menu.Root>; } export function DropdownMenuTrigger(props: Menu.Trigger.Props) { return <Menu.Trigger {...props} />; } export function DropdownMenuContent(props: Menu.Popup.Props) { return ( <Menu.Portal> <Menu.Positioner align="end" sideOffset={4}> <Menu.Popup className="z-50 min-w-32 rounded-lg bg-background p-1 shadow-lg ring-1 ring-foreground/10" {...props} /> </Menu.Positioner> </Menu.Portal> ); } export function DropdownMenuGroup(props: Menu.Group.Props) { return <Menu.Group {...props} />; } export function DropdownMenuItem(props: Menu.Item.Props) { return ( <Menu.Item className="flex cursor-default items-center rounded-md px-2 py-1.5 text-sm outline-none focus:bg-secondary" {...props} /> ); } src/components/theme-changer.tsx — the full component:
import { Moon, Sun } from "lucide-react"; import { useTheme } from "@/components/providers/theme-provider"; import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuTrigger, } from "@/components/ui/theme-menu"; export function ThemeChanger() { const { setTheme } = useTheme(); return ( <DropdownMenu> <DropdownMenuTrigger render={<Button variant="secondary" size="icon-lg" />} > <Sun className="inline-block dark:hidden" /> <Moon className="hidden dark:inline-block" /> <span className="sr-only">Toggle theme</span> </DropdownMenuTrigger> <DropdownMenuContent> <DropdownMenuGroup> <DropdownMenuItem onClick={() => setTheme("light")}> Light </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("dark")}> Dark </DropdownMenuItem> <DropdownMenuItem onClick={() => setTheme("system")}> System </DropdownMenuItem> </DropdownMenuGroup> </DropdownMenuContent> </DropdownMenu> ); } The render prop tells Base UI to use your Button as the trigger, so keyboard and ARIA behavior stay on a real button. The two icons are plain markup: CSS decides which one is visible from the same .dark class the boot script set.
Now three patterns you can drop into any route.
Put the chooser where people expect it
import { ThemeChanger } from "@/components/theme-changer"; export function SiteHeader() { return ( <header className="flex items-center justify-between border-b px-4 py-3"> <span className="font-medium">Docs</span> <ThemeChanger /> </header> ); } One component offers all three choices, and its icon is already correct on the first frame.
Icons that flip without JavaScript state
export function ThemeGlyph() { return ( <span aria-hidden="true" className="inline-block h-4 w-4"> <svg className="block h-4 w-4 dark:hidden" viewBox=<...