ReactMedium

Dark mode toggle

A dark mode toggle stores the user's preference ("light", "dark" or "system"), applies it by setting a class or data-theme attribute on <html> that switches CSS variables, follows prefers-color-scheme when set to system, persists the choice in localStorage (or a cookie for server rendering), and avoids a flash of the wrong theme by applying it before React hydrates.

Steps

  1. CSS variables: :root { --bg: white; --fg: black; } and [data-theme="dark"] { --bg: #0b1020; --fg: #f8fafc; }; set color-scheme so form controls and scrollbars match.
  2. State: "light" | "dark" | "system" with lazy initialization from localStorage.
  3. Resolve system: matchMedia("(prefers-color-scheme: dark)"), listening for changes.
  4. Apply: an effect sets document.documentElement.dataset.theme to the resolved theme.
  5. Persist: save the preference on change.
  6. No flash: a small inline script in <head> sets the attribute before first paint; in SSR apps read a cookie on the server. Libraries such as next-themes do this.

Details

  • Tailwind v4: @custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)); to drive dark: utilities from the attribute.
  • Give the toggle an accessible name and state (aria-pressed or a labeled select).
  • Respect the system setting by default.
  • Images and charts may need dark variants.

Code example

tsx
1import { useEffect, useState } from "react";
2
3type Pref = "light" | "dark" | "system";
4
5function getSystem() {
6 return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
7}
8
9export function useTheme() {
10 const [pref, setPref] = useState<Pref>(() => (localStorage.getItem("theme") as Pref) ?? "system");
11 const [system, setSystem] = useState<"light" | "dark">(getSystem);
12
13 useEffect(() => {
14 const mql = window.matchMedia("(prefers-color-scheme: dark)");
15 const onChange = () => setSystem(mql.matches ? "dark" : "light");
16 mql.addEventListener("change", onChange);
17 return () => mql.removeEventListener("change", onChange);
18 }, []);
19
20 const resolved = pref === "system" ? system : pref;
21
22 useEffect(() => {
23 document.documentElement.dataset.theme = resolved;
24 document.documentElement.style.colorScheme = resolved;
25 localStorage.setItem("theme", pref);
26 }, [pref, resolved]);
27
28 return { pref, setPref, resolved };
29}
30
31export function ThemeToggle() {
32 const { pref, setPref, resolved } = useTheme();
33 return (
34 <label>
35 Theme ({resolved}){" "}
36 <select value={pref} onChange={(e) => setPref(e.target.value as Pref)}>
37 <option value="system">System</option>
38 <option value="light">Light</option>
39 <option value="dark">Dark</option>
40 </select>
41 </label>
42 );
43}
44
45// In index.html <head>, before the app loads, to avoid a flash:
46// <script>document.documentElement.dataset.theme = (localStorage.theme === "dark" || (localStorage.theme !== "light" && matchMedia("(prefers-color-scheme: dark)").matches)) ? "dark" : "light";</script>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app