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
- CSS variables:
:root { --bg: white; --fg: black; }and[data-theme="dark"] { --bg: #0b1020; --fg: #f8fafc; }; setcolor-schemeso form controls and scrollbars match. - State:
"light" | "dark" | "system"with lazy initialization fromlocalStorage. - Resolve system:
matchMedia("(prefers-color-scheme: dark)"), listening for changes. - Apply: an effect sets
document.documentElement.dataset.themeto the resolved theme. - Persist: save the preference on change.
- 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 asnext-themesdo this.
Details
- Tailwind v4:
@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));to drivedark:utilities from the attribute. - Give the toggle an accessible name and state (
aria-pressedor a labeled select). - Respect the system setting by default.
- Images and charts may need dark variants.
Code example
tsx
1import { useEffect, useState } from "react";23type Pref = "light" | "dark" | "system";45function getSystem() {6 return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";7}89export function useTheme() {10 const [pref, setPref] = useState<Pref>(() => (localStorage.getItem("theme") as Pref) ?? "system");11 const [system, setSystem] = useState<"light" | "dark">(getSystem);1213 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 }, []);1920 const resolved = pref === "system" ? system : pref;2122 useEffect(() => {23 document.documentElement.dataset.theme = resolved;24 document.documentElement.style.colorScheme = resolved;25 localStorage.setItem("theme", pref);26 }, [pref, resolved]);2728 return { pref, setPref, resolved };29}3031export 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}4445// 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.