getThemeInitScript

Set the theme before the first paint, to avoid a flash.

getThemeInitScript({ storageKey, defaultTheme })

Returns JavaScript source that sets <html data-theme> before the page paints, with the same rules as `ThemeProvider`: the saved choice, otherwise defaultTheme, with system resolved from the device. ThemeProvider only applies the theme after the app has hydrated, so without this a visitor whose saved or default theme differs from the browser default can see the wrong theme for a moment. Put the result in an inline script in the document head, and pass the same storageKey and defaultTheme as the provider. The values are JSON-encoded, so any key is safe.

import { getThemeInitScript } from 'xedonium'

// Next.js pages router: pages/_document.tsx
<Head>
	<script dangerouslySetInnerHTML={{ __html: getThemeInitScript({ storageKey: 'my-app-theme', defaultTheme: 'light' }) }} />
</Head>

// Vite / plain HTML: build the string once and paste it into index.html
// <script>…the returned source…</script>

API

Parameters

  • storageKeystring
    Default: 'xedonium-theme-override'

    Must match the ThemeProvider.

  • defaultTheme'light' | 'dark' | 'system'
    Default: 'system'

    Must match the ThemeProvider.

Returns

  • scriptstring

    JavaScript source for an inline <script>.

See also:Foundations: Theme