Skip to content
Primitives

Theme Switcher

System / light / dark tri-state that drives the .dark class and persists to localStorage, with a View-Transitions circular reveal from the clicked control. Exports a useTheme hook too.

MotionlayoutId pill indicator; View Transitions circular reveal on switch

Install

Install Kineto and follow the theme setup once in your app.

bash
npm install kineto
tsx
import { useTheme, ThemeSwitcher } from "kineto/theme-switcher";

Preview

System · Light · Dark — watch the circular reveal. (This controls the docs theme.)

tsx
"use client";

import * as React from "react";
import { Monitor, Moon, Sun } from "lucide-react";
import { motion } from "motion/react";

import { cn } from "@/lib/cn";
import { spring } from "@/lib/motion-presets";

/* A canonical theme control: system / light / dark tri-state that drives the `.dark` class and
 * persists to localStorage. Switching uses the View Transitions API for a circular reveal from the
 * clicked control (falls back to an instant swap when unsupported or reduced-motion). The `useTheme`
 * hook is exported too, for wiring the same state elsewhere. */

export type Theme = "system" | "light" | "dark";

const STORAGE_KEY = "theme";

function systemPrefersDark() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-color-scheme: dark)").matches;
}

function resolve(theme: Theme): "light" | "dark" {
  return theme === "system" ? (systemPrefersDark() ? "dark" : "light") : theme;
}

function applyTheme(theme: Theme) {
  document.documentElement.classList.toggle("dark", resolve(theme) === "dark");
}

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

export function useTheme() {
  const [theme, setThemeState] = React.useState<Theme>("system");
  const [mounted, setMounted] = React.useState(false);

  React.useEffect(() => {
    setMounted(true);
    const stored = (typeof localStorage !== "undefined" && localStorage.getItem(STORAGE_KEY)) as Theme | null;
    if (stored === "light" || stored === "dark" || stored === "system") setThemeState(stored);
  }, []);

  // Track OS changes while following the system.
  React.useEffect(() => {
    if (theme !== "system") return;
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    const onChange = () => applyTheme("system");
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, [theme]);

  const setTheme = React.useCallback((next: Theme, origin?: { x: number; y: number }) => {
    const apply = () => {
      setThemeState(next);
      try {
        localStorage.setItem(STORAGE_KEY, next);
      } catch {
        /* ignore storage failures */
      }
      applyTheme(next);
    };

    // NB: call `startViewTransition` ON `document` — detaching it into a variable drops its
    // `this` binding and throws "Illegal invocation", which would abort the whole theme change.
    const doc = document as Document & {
      startViewTransition?: (cb: () => void) => { ready: Promise<void> };
    };

    if (origin && doc.startViewTransition && !prefersReducedMotion()) {
      doc
        .startViewTransition(apply)
        .ready.then(() => {
          const { x, y } = origin;
          const radius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
          document.documentElement.animate(
            { clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`] },
            { duration: 450, easing: "ease-in-out", pseudoElement: "::view-transition-new(root)" }
          );
        })
        .catch(() => {
          /* animation unsupported — theme already applied */
        });
    } else {
      apply();
    }
  }, []);

  return { theme, setTheme, mounted };
}

const OPTIONS: { value: Theme; icon: typeof Sun; label: string }[] = [
  { value: "system", icon: Monitor, label: "System" },
  { value: "light", icon: Sun, label: "Light" },
  { value: "dark", icon: Moon, label: "Dark" },
];

export interface ThemeSwitcherProps extends React.HTMLAttributes<HTMLDivElement> {}

const ThemeSwitcher = React.forwardRef<HTMLDivElement, ThemeSwitcherProps>(
  ({ className, ...props }, ref) => {
    const { theme, setTheme, mounted } = useTheme();
    const layoutId = React.useId();

    return (
      <div
        ref={ref}
        role="radiogroup"
        aria-label="Color theme"
        className={cn("inline-flex items-center gap-1 rounded-full border border-border bg-card p-1", className)}
        {...props}
      >
        {OPTIONS.map((opt) => {
          const active = mounted && theme === opt.value;
          const Icon = opt.icon;
          return (
            <button
              key={opt.value}
              type="button"
              role="radio"
              aria-checked={active}
              aria-label={opt.label}
              title={opt.label}
              onClick={(e) => setTheme(opt.value, { x: e.clientX, y: e.clientY })}
              className={cn(
                "relative inline-flex size-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:text-foreground",
                active && "text-foreground"
              )}
            >
              {active ? (
                <motion.span
                  layoutId={layoutId}
                  transition={spring.snappy}
                  className="absolute inset-0 rounded-full bg-muted"
                />
              ) : null}
              <Icon className="relative size-4" />
            </button>
          );
        })}
      </div>
    );
  }
);
ThemeSwitcher.displayName = "ThemeSwitcher";

export { ThemeSwitcher };

src/components/ui/theme-switcher.tsx

Props

PropTypeDefaultDescription
useTheme()() => { theme, setTheme, mounted }—Hook to read/set the theme from anywhere.