Web · APIs and utilities
Theme
Manages the app's theme: stores the user preference, follows the system preference, syncs across tabs and applies the theme to the <html> element.
Live example
Preview
Code
Events
- Events appear here when you interact with the preview.
Import
Manages the app's theme: stores the user preference, follows the system preference, syncs across tabs and applies the theme to the <html> element.
It also prevents the wrong theme from flashing on first page load: it adds a small inline script to the server output that applies the theme before the content. You do not need to add anything to <head>. The script is removed from the DOM after hydration; when rendered from scratch on the client it is not added at all (React does not run such scripts and warns). For apps without server output use getThemeScript.
Place it inside <body> in the root layout, outermost around the content. Add suppressHydrationWarning to <html>, because the script changes that element's attributes before React takes over. Use the useTheme hook to change the theme.
Nesting: If a section or page wants a different theme, wrap it in a ThemeProvider too. Since the theme is applied to <html>, the innermost mounted provider wins; when it unmounts (e.g. on leaving the page) the outer one's theme comes back automatically. Dialogs and notifications get the right theme too. useTheme reads the nearest provider.
- Pinning a page to one theme: pass
forcedTheme; the preference is neither read nor written. - Giving a section its own preference (e.g. an admin panel): pass a different
storageKey. With the same key the user's choice is shared across sections; a choice not in the section'sthemeslist falls back todefaultTheme.
Examples
Shows theme-dependent content (theme picker label, selected button, sun/moon icon) correctly on first page load too, with no server/client difference (hydration mismatch) or flashing.
The server cannot know the user's preference, so useTheme returns undefined on the first render and a label using it directly first shows the wrong theme name and then changes. ThemeView instead renders the content once per theme on the first render and hides, via CSS, the ones not matching the theme the inline script wrote to <html>. After hydration only the current theme's content remains; that copy is not recreated and keeps its state.
Content is wrapped in a <span> with display: contents; it does not affect layout. Do not use it where a <span> is not allowed, such as a table row.
Examples
createColorScale
function50–950 shade scale of a color (equal perceptual steps in OKLCH). The color itself is placed on the step closest to its lightness; the other steps are derived from there. Chroma is clipped to fit in sRGB.
Examples
createTheme
functionGenerates all color tokens of the light and dark themes from a single primary color: grays such as background, card, border and muted text are slightly tinted toward the primary; the text color on filled colors is chosen by contrast; for the dark theme colors are lightened enough to stay readable. The result also includes a WCAG contrast check of important pairs.
Pure function; runs on the server. Convert the output to CSS with themeToCss or pass it to a container as style.
Examples
checkContrast
functionWCAG contrast of important text/background pairs in theme tokens. At least 4.5 is required for text pairs and at least 3 for the primary against the background. Can also be used to check tokens you wrote by hand (values are oklch() or strings parseColor understands).
themeToCss
functionConverts a createTheme result into text to paste into the project's CSS file.
Examples
themeToStyle
functionConverts theme tokens into variables for a container's style prop; to draw part of the page (e.g. a preview) with that theme.
Examples
useTheme
functionReads and changes the current theme. Must be used inside ThemeProvider.
theme and resolvedTheme return undefined on the server and during the first hydration, because the user preference is only known in the browser. Render UI that displays the selected theme (theme picker label, pressed button, sun/moon icon) with ThemeView; then the right theme shows on first page load too, with no server/client mismatch.
Examples
getThemeScript
functionReturns the source of the inline script that applies the theme before the page paints.
ThemeProvider adds this script to the server output itself; apps rendered on the server such as Next.js do not need this function. Use it only in apps without server output (e.g. a Vite single-page app) to put the text in a <script> tag in index.html.
ThemeConfig
interfaceTheme configuration. ThemeProvider uses these options both for its own state and for the anti-flicker script it embeds in the page.
| Name | Type | Default | Description |
|---|---|---|---|
themes? | readonly string[] | ["light", "dark"] | Available theme names. "system" is not listed here; it is enabled separately with enableSystem. |
darkThemes? | readonly string[] | ["dark"] | Themes with a dark color scheme. While one of them is active, the dark class is added to <html> and color-scheme: dark is applied. |
defaultTheme? | string | "system"` (`"light"` if `enableSystem` is off) | Theme used when there is no stored preference. |
enableSystem? | boolean | true | Enables the "system" option. When selected, the OS light/dark preference is followed and the theme updates instantly when it changes. |
storageKey? | string | "ui-theme" | Key under which the user preference is stored in localStorage. |
forcedTheme? | string | When given, the user preference is ignored and this theme is always applied. Useful for pinning certain pages to a single theme. |
ThemeTokenName
typeNames of the color tokens in the createTheme output (--ui-<name>).
ThemeTokens
typeToken values of a color scheme (light or dark); oklch() strings.
PaletteStep
typeSteps of the shade scale (same names as Tailwind).
ColorScale
type50–950 shade scale of a color; oklch() strings.
CreateThemeOptions
interfacecreateTheme options.
| Name | Type | Default | Description |
|---|---|---|---|
primary | string | Primary (brand) color; a hex, rgb, hsl or oklch string CSS understands. Used as is in the light theme; lightened enough to stay readable in the dark theme (see primaryDark). | |
primaryDark? | string | Primary color in the dark theme. Derived from primary when omitted. | |
neutralTint? | number | 0.3 | How much the grays (background, border, muted text) are tinted toward the primary color: 0 is pure gray, 1 clearly tinted. |
neutralHue? | number | Hue of the grays (oklch degrees, 0–360). Defaults to the primary color's hue; 285 (the library default) when the primary is gray. | |
accent? | "neutral" | "primary" | "neutral" | Hover and selected item background (accent) color. - "neutral": gray (the library default). - "primary": a very light (dark in the dark theme) shade of the primary. |
destructive? | string | Danger color (delete, error). Defaults to the library's red. | |
success? | string | Success color. Defaults to the library's green. | |
warning? | string | Warning color. Defaults to the library's yellow. | |
radius? | number | string | 0.625 | Corner radius (--ui-radius): a number is rem (0.5), a string is written as is ("8px"). |
ContrastCheck
interfaceWCAG contrast result of a text/background pair.
| Name | Type | Description |
|---|---|---|
scheme | "light" | "dark" | Which theme: light or dark. |
foreground | ThemeTokenName | Text token. |
background | ThemeTokenName | Background token. |
ratio | number | Contrast ratio (1–21). |
min | number | Minimum required ratio: 4.5 for text (WCAG AA), 3 for the primary color against the background (non-text element such as a button border). |
pass | boolean | ratio >= min. |
GeneratedTheme
interfaceResult of createTheme.
| Name | Type | Description |
|---|---|---|
light | ThemeTokens | Light theme tokens. |
dark | ThemeTokens | Dark theme tokens. |
radius | string | --ui-radius value. |
scale | ColorScale | 50–950 shade scale of the primary color. |
contrast | ContrastCheck[] | Contrast check of important text/background pairs, for both themes. |
ThemeToCssOptions
interfacethemeToCss options.
| Name | Type | Default | Description |
|---|---|---|---|
name? | string | Theme name. When given, [data-theme="name"] (light) and [data-theme="name-dark"] (dark) blocks are written; add them to ThemeProvider's themes and darkThemes lists. When omitted, the default light and dark themes are overridden (:root and .dark). | |
scale? | boolean | false | Also write the primary color's shade scale (--ui-primary-50 … --ui-primary-950) and register it with Tailwind (for classes like bg-primary-100). |
SetThemeOptions
interfaceExtra options for ThemeContextValue.setTheme.
| Name | Type | Description |
|---|---|---|
transition? | ThemeTransition | Animation for this change; overrides the provider's transition. |
origin? | ThemeTransitionOrigin | Origin of spreading animations (an element, a click event or a coordinate). Defaults to the last clicked spot, or the focused element if there is none; you rarely need to pass it. |
ThemeContextValue
interfaceReturn value of the useTheme hook.
| Name | Type | Description |
|---|---|---|
theme | string | undefined | The selected theme; may be "system". Returns undefined on the server and during the first hydration because the user preference is not known yet (returns forcedTheme if set). Use ThemeView for UI that displays this value; otherwise the wrong theme shows first on page load. |
resolvedTheme | string | undefined | The theme actually applied. If "system" is selected it resolves to "light" or "dark". Returns undefined on the server and during the first hydration. |
systemTheme | "light" | "dark" | undefined | The OS preference: "light", "dark", or undefined on the server. |
themes | readonly string[] | Selectable themes. If enableSystem is on, "system" is included at the end. |
forcedTheme | string | undefined | Name of the forced theme, if any. |
setTheme | (theme: string | ((current: string) => string), options?: SetThemeOptions) => void | Changes the theme and stores the preference. Other open tabs of the same site update instantly. If the provider has a transition, the change is animated, starting from the clicked element. |
ThemeProviderProps
interfaceProps of the ThemeProvider component.
| Name | Type | Default | Description |
|---|---|---|---|
children? | ReactNode | App content that uses the theme. | |
disableTransitionOnChange? | boolean | true | Temporarily disables CSS transitions while the theme changes. |
transition? | ThemeTransition | "none" | Animation played when the user changes the theme (useTheme setTheme). Pass a type name ("ripple") or settings with duration and easing ({ type: "ripple", duration: 900 }). - "ripple": like a water drop, spreads in a wave from the clicked element. - "circle": spreads from the clicked element as a sharp circle. - "fade": slow, soft transition. - "wipe": comes down from the top like a curtain. - "blur": changes by blurring. Uses the browser's View Transitions API (smoothness details: ThemeTransitionType). If the chosen theme does not change the appearance (e.g. from dark to "system" that is currently dark), no animation plays. In unsupported browsers and for users who prefer reduced motion the theme changes instantly. A theme changed by the system preference or another tab is applied without animation. |
nonce? | string | If you use a Content Security Policy (CSP), the nonce for the inline anti-flicker script and the inline style added for ThemeView. | |
themes? | readonly string[] | ["light", "dark"] | Available theme names. "system" is not listed here; it is enabled separately with enableSystem. |
darkThemes? | readonly string[] | ["dark"] | Themes with a dark color scheme. While one of them is active, the dark class is added to <html> and color-scheme: dark is applied. |
defaultTheme? | string | "system"` (`"light"` if `enableSystem` is off) | Theme used when there is no stored preference. |
enableSystem? | boolean | true | Enables the "system" option. When selected, the OS light/dark preference is followed and the theme updates instantly when it changes. |
storageKey? | string | "ui-theme" | Key under which the user preference is stored in localStorage. |
forcedTheme? | string | When given, the user preference is ignored and this theme is always applied. Useful for pinning certain pages to a single theme. |
ThemeViewProps
interfaceProps of the ThemeView component.
| Name | Type | Default | Description |
|---|---|---|---|
children | (theme: string) => ReactNode | Content to render per theme. Receives the selected (or, with resolved, the applied) theme name. | |
resolved? | boolean | false | When true, the theme actually applied is given instead of the selected one: "light" or "dark" while "system" is selected. Use it for appearance-dependent content such as a sun/moon icon. |
Animations that can play on theme change.
"none": changes instantly."fade": the new theme slowly appears (soft transition)."ripple": water drop; a drop in the new theme's color falls on the clicked spot and the new theme spreads from there as a single circle. The circle's edge is a rippling water edge; a bright wave crest moves ahead of it and calms as it spreads."circle": spreads from the clicked element as a sharp-edged circle without rings; the lightest spreading animation."wipe": the new theme comes down from the top like a curtain."blur": the old theme blurs while the new one appears over it.
Smoothness: fade and blur only use opacity and filters, so they run on the GPU and at full speed on 120 Hz screens too. ripple, circle and wipe reveal part of the screen by clipping; current Chromium-based browsers also run this clipping on the GPU. In browsers that cannot, the page is repainted every frame and may stay at 60 fps on 120 Hz screens. For the most reliable smoothness use fade.
If the chosen theme does not change the appearance (e.g. switching from dark to "system" that is currently dark), no animation plays.
ThemeTransitionOptions
interfaceDetailed settings of a theme transition.
| Name | Type | Default | Description |
|---|---|---|---|
type | ThemeTransitionType | Animation type. | |
duration? | number | fade` 500, `ripple` 900 (including the drop's fall), `circle` 550, `wipe` 600, `blur` 500 | Duration (milliseconds). |
easing? | string | A soft curve chosen per type. | CSS easing curve. |
ThemeTransition
typeA theme transition: just a type name or detailed settings.
Origin of spreading animations (ripple, circle): an element (starts from its center), a mouse/touch event or a screen coordinate.