DEV Community

Cover image for Managing Theme in TanStack Start App
Saiful Islam
Saiful Islam

Posted on Edited on

Managing Theme in TanStack Start App

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

The stylesheet is equally simple:

:root {
  --background: #ffffff;
}

.dark {
  --background: #09090b;
}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Three fixes come to mind, and each one moves the problem.

  1. 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"
   );
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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");
   }, []);
Enter fullscreen mode Exit fullscreen mode
  1. Use useLayoutEffect or 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");
   }, []);
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 and colorScheme decide what the audience sees. React context holds the note — the requested Theme — 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 says system.
  • 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 through matchMedia.

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
Enter fullscreen mode Exit fullscreen mode
src/
├── components/
│   ├── providers/
│   │   └── theme-provider.tsx
│   ├── theme-changer.tsx
│   └── ui/
│       └── theme-menu.tsx
├── routes/
│   └── __root.tsx
└── styles.css
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

@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;
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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}
    />
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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="0 0 16 16">
        <circle cx="8" cy="8" r="4" fill="currentColor" />
      </svg>
      <svg className="hidden h-4 w-4 dark:block" viewBox="0 0 16 16">
        <path d="M13 10A6 6 0 0 1 6 3a6 6 0 1 0 7 7Z" fill="currentColor" />
      </svg>
    </span>
  );
}
Enter fullscreen mode Exit fullscreen mode

The dark: variant reads the same class the boot script set, so the icon is right on the first frame and cannot disagree with hydration.

Show the stored choice, not a guess

import { useTheme } from "@/components/providers/theme-provider";

const labels = {
  light: "Light",
  dark: "Dark",
  system: "System",
} as const;

export function ThemeStatus() {
  const { theme } = useTheme();

  return <span className="text-sm">Theme: {labels[theme]}</span>;
}
Enter fullscreen mode Exit fullscreen mode

Context holds intent, so the label keeps saying "System" even when the OS quietly flips the pixels.

❌ Do not echo theme back into storage in an effect: setTheme already writes it, and a render-time storage read is the bug that broke server rendering in the first place.

When to Use It

Reach for it only when all three are true:

  • You server-render or prerender, and people can choose light, dark, or system.
  • You control the document shell and can place one inline script before route content.
  • Your CSS can key off a class on the root element.
Situation Better tool
Client-only app with no server rendering Plain state plus one effect
Per-card or per-panel themes CSS variables scoped to that container
Theme must be known while generating HTML on server Cookie or session value read server-side
OS preference is the only option @media (prefers-color-scheme: dark) in CSS
Several tabs must stay in sync Add a storage event listener
JavaScript needs the resolved mode before first paint Publish it as a DOM attribute in the boot script

Smell test: if your dark mode is decided after the first pixel, you are already debugging a flash.

How It Works Under the Hood

  1. The context holds intent. createContext({ theme: "system", setTheme: () => {} }) gives useTheme() a safe default outside a provider. It carries the request, never the painted result, so a system user stays system when the OS changes.

  2. The boot script paints before hydration. getThemeScript uses JSON.stringify for the key and fallback, so developer-supplied strings cannot break the JS literals. It validates the stored value, resolves system through matchMedia, and writes a class plus style.colorScheme; try/catch degrades blocked storage to the default. It only adds a class because it runs once on a fresh document, while applyTheme removes both classes because it can run many times.

  3. Two microtasks replace a render-time read. The mount effect reads storage, then queues setCurrentTheme and setMounted; React 19 batches them into one render, so mounted is never true with the wrong theme. The same read during render would touch localStorage on the server.

  4. Effect order handles OS changes. The apply effect runs after mount. The listener effect subscribes only while currentTheme === "system" and cleans up on change, so a fixed theme stops the subscription. An OS flip between boot script and hydration is harmless: the boot class is already right and the mount effect re-applies it.

  5. The cost is small but real. Every render creates a new context value object and a new setTheme function; each user choice performs one storage write; each change writes two class operations plus an inline style; a system user retains one media listener. Memoize consumers if that object identity matters.

Phase currentTheme in React Class on <html> Decided by
Server render defaultTheme none in markup initial state
HTML parse not hydrated dark inline script
First paint defaultTheme dark CSS
Hydration commit defaultTheme dark React
Mount microtask stored dark dark applyTheme
OS change while system system flips to light media listener
Interrupted render proposed value, dropped last committed React batching

Server rendering stays clean: DOM APIs live in effects or inside the script string, never in render, and server and first client render both start at defaultTheme. If React markup depends on the resolved mode, publish it as a data-theme attribute in the boot script and read that after mount.

None of the built-ins solve this. useSyncExternalStore subscribes to matchMedia but needs a server snapshot and cannot act before hydration. useLayoutEffect runs before client paint only and warns during server rendering. React 19's useEffectEvent stabilizes callback identity, not the first frame. A CSS media query cannot honor a stored choice.

Conclusion

The trade is a duplicated script in every HTML response in exchange for a correct first frame. You give up the idea that React owns the switch; you gain a page that never shows the wrong theme and a context that stays authoritative for future changes.

  • Keep intent in context and the painted result on <html>; never mix the two.
  • Validate stored values and wrap boot-time storage access in try/catch.
  • Unsubscribe from OS changes as soon as the user picks a fixed theme.

This belongs wherever server-rendered pages offer a theme choice. For a client-only toy with no user preference, a plain CSS media query is the boring answer, and it wins.

Top comments (0)