useTheme

A theme management hook that handles light, dark, and system theme preferences. Persists selection to localStorage and applies the appropriate class to the document root.

Preview

Current theme:
light
Resolved:
light

Usage

tsx
import { useTheme } from "zostel-ui";

function ThemeToggle() {
  const { theme, resolvedTheme, setTheme, toggleTheme } = useTheme();

  return (
    <div>
      <p>Current: {theme}</p>
      <p>Resolved: {resolvedTheme}</p>

      <button onClick={() => setTheme("light")}>Light</button>
      <button onClick={() => setTheme("dark")}>Dark</button>
      <button onClick={() => setTheme("system")}>System</button>

      <button onClick={toggleTheme}>Toggle</button>
    </div>
  );
}

Parameters

Parameter Type Default Description
defaultTheme "light" | "dark" | "system" "light" Initial theme when no localStorage value exists

Return Value

Property Type Description
theme "light" | "dark" | "system" The current theme setting as selected by the user
resolvedTheme "light" | "dark" The actual theme applied (resolves "system" to light/dark)
setTheme (theme: Theme) => void Set the theme to light, dark, or system
toggleTheme () => void Toggle between light and dark (resolves system first)

How It Works

ts
// 1. Reads initial theme from localStorage ("zostel-ui-theme")
// 2. Falls back to the defaultTheme parameter
// 3. Adds "light" or "dark" class to <html> element
// 4. Listens for OS-level prefers-color-scheme changes
//    when theme is set to "system"
// 5. Persists selection to localStorage on every change