Skip to content

Dark mode with no flash

Loja Aurora's staff closes the register at ten at night, and the white dashboard tires the eyes. You want three options, Claro (light), Escuro (dark) and Sistema (system), you want the choice to survive F5 and, above all, you want the page not to flash white before turning dark. 🌙

The flash happens because the HTML paints before React mounts. For an instant the default theme shows, and only then does ThemeProvider fix it. The cure is a small, synchronous script in the <head>, generated by themeInitScript(), that applies the theme before the first paint.

Before you start

Install in manual install. The SDK components already read the --tempest-* tokens, so they change colour on their own.

What we are building

  • 🎛️ A Light / Dark / System switcher at the top of the dashboard.
  • 💾 The choice saved in localStorage, read again on the next visit.
  • ⚡ Zero flash on load, even with F5 and a slow connection.
  • 🖥️ In System mode, the dashboard follows the operating system in real time.
  • 📱 The browser bar on phones follows the theme (theme-color).

The code, file by file

1. The script in the <head>

// vite.config.ts
import { createViteConfig, tempestCsp, tempestThemeInit } from "tempest-react-sdk/vite";

export default createViteConfig({
  plugins: [tempestThemeInit(), tempestCsp()],
});

tempestThemeInit() writes the script at the top of index.html's <head>, under vite dev and in the build. index.html stays as it is, with no hand-pasted script. The app create-tempest-app generates already ships this line.

// src/Document.tsx
import type { ReactNode } from "react";
import { themeInitScript } from "tempest-react-sdk";

interface DocumentProps {
  children: ReactNode;
}

export function Document({ children }: DocumentProps) {
  return (
    <html lang="pt-BR">
      <head>
        <meta charSet="UTF-8" />
        <title>Painel · Loja Aurora</title>
        <script dangerouslySetInnerHTML={{ __html: themeInitScript() }} />
      </head>
      <body>{children}</body>
    </html>
  );
}

2. The theme switcher

// src/components/ThemeSwitcher.tsx
import { SegmentedControl, useTheme, type ThemeMode } from "tempest-react-sdk";

const options: { value: ThemeMode; label: string }[] = [
  { value: "light", label: "☀️ Claro" },
  { value: "dark", label: "🌙 Escuro" },
  { value: "system", label: "💻 Sistema" },
];

export function ThemeSwitcher() {
  const { theme, setTheme } = useTheme();

  return (
    <SegmentedControl
      aria-label="Tema do painel"
      size="sm"
      options={options}
      value={theme}
      onChange={setTheme}
    />
  );
}

3. The app

// src/App.tsx
import { AppProviders, AppRouter, Spinner } from "tempest-react-sdk";
import { routes } from "@/routes";

export function App() {
  return (
    <AppProviders
      theme={{
        defaultTheme: "system",
        themeColor: { light: "#ffffff", dark: "#0b0d12" },
      }}
      errorBoundary={{ fallback: <p>Algo deu errado. Recarregue a página.</p> }}
    >
      <AppRouter routes={routes} fallback={<Spinner />} />
    </AppProviders>
  );
}

4. The app's own CSS

/* src/styles/app.css */
.topbar {
  background: var(--tempest-surface);
  color: var(--tempest-text);
  border-bottom: 1px solid var(--tempest-border);
}

[data-tempest-theme="dark"] .logo {
  filter: invert(1);
}

Piece by piece

The script is what kills the flash

It runs before the CSS and before React. It reads the choice saved in localStorage["tempest-theme"]. If it is "system" or there is nothing, it asks the browser through prefers-color-scheme. At the end, it writes data-tempest-theme="dark" (or "light") on <html>. When the first paint happens, the tokens are already right.

In the Vite tab, the tempestThemeInit() plugin injects what themeInitScript() returns. In the SSR tab, you inject the function itself. Either way the script never drifts from the SDK.

Synchronous and early, always

No defer, no async, no script at the end of <body>. It must run before the first paint, or the flash comes back.

With tempestCsp(), the inline script is already allowed

The SDK's CSP plugin computes the SHA-256 of every inline script in index.html, including the one tempestThemeInit() injects, and adds it to the policy. You do not need 'unsafe-inline'. See Inline scripts enter by hash.

The switcher uses the theme context

useTheme() returns:

  • theme: the raw choice ("light", "dark" or "system"), which is what the switcher shows;
  • resolvedTheme: what is actually applied ("light" or "dark");
  • setTheme(next): saves the choice to localStorage and updates <html>;
  • toggle(): flips between light and dark, for when a single button is enough.

SegmentedControl takes value={theme} and onChange={setTheme} directly, because both speak the same ThemeMode type. See SegmentedControl.

The provider already ships in <AppProviders>

<AppProviders> mounts ThemeProvider by default. The theme prop only tunes it:

  • defaultTheme: "system" applies to whoever never chose anything. In system mode, the provider listens to prefers-color-scheme and switches the moment the operating system changes.
  • themeColor updates <meta name="theme-color">, which paints the browser bar on Android and the installed app's status bar. 📱 When the page has no such tag, the provider creates it in the <head>.

Same key on both sides

The script and the provider must read the same localStorage key. Both use "tempest-theme" by default. If you change it, pass storageKey to both: tempestThemeInit({ storageKey: "aurora-theme" }) (or themeInitScript({ storageKey: "aurora-theme" }) under SSR) and theme={{ storageKey: "aurora-theme" }}.

Your CSS uses the same tokens

The SDK components read --tempest-bg, --tempest-surface, --tempest-text and the other tokens. Use the same ones in the app's CSS, and it switches along. For something a token does not solve, such as inverting a logo, the [data-tempest-theme="dark"] selector works. The dark theme is always that attribute, never class="dark". See Customizing tokens.

Recap

  • ✅ tempestThemeInit() in vite.config.ts (or themeInitScript() under SSR) puts the script in the <head>, which applies the theme before the first paint: no flash.
  • ✅ useTheme() gives theme, resolvedTheme, setTheme and toggle.
  • ✅ SegmentedControl + setTheme become the Light / Dark / System switcher.
  • ✅ <AppProviders theme={{ defaultTheme, themeColor }}> follows the system and paints the phone's bar.
  • ✅ App CSS with --tempest-* tokens and [data-tempest-theme="dark"].