|Kit

useTheme

Reads and sets the persisted light, dark or system choice, keeping data-theme on the html element in sync across tabs and with the OS.

useTheme manages a persisted "light" | "dark" | "system" choice and keeps data-theme on <html> in sync with it. Reach for it when you build a theme switch. Setting the theme up for an app (the blocking script that prevents a flash of the wrong theme on first load) is covered in Theming.

import { useTheme } from '@42-central/ui-react';

const { mode, resolvedTheme, setMode } = useTheme();

<button onClick={() => setMode(resolvedTheme === 'dark' ? 'light' : 'dark')}>
  <SunIcon className="dark:hidden" />
  <MoonIcon className="hidden dark:block" />
</button>

Usage

This switch drives this site's theme. The choice is saved in localStorage, so it follows you to another tab and survives a reload. system follows your OS setting live.

Loading the stored choice…

Code

const { mode, resolvedTheme, setMode } = useTheme();

<SegmentGroup
  data={['light', 'dark', 'system']}
  value={mode}
  onChange={(next) => next && setMode(next)}
/>
<p>mode: {mode} · resolvedTheme: {resolvedTheme}</p>

setMode also takes an updater resolved against the current mode, like useState's setter: setMode((m) => NEXT[m]) cycles through the three.

Don't render resolvedTheme

A server can't know the visitor's preference: resolvedTheme is "light" in the server HTML and on the first client render, and mode is defaultColorScheme, so anything rendered from them shows the wrong theme until hydration. Read them for logic (what a click switches to), and paint the visible state with the dark: variant, which keys off the same data-theme attribute and is right from the first frame. The demo above renders its readout only after hydration for that reason.

API

Prop

Type

Prop

Type

Every option is detailed, with the Next.js and Vite setups, in Theming's API reference.

On this page