Dark Mode Toggle Hook

A custom React hook to toggle light/dark mode and persist the preference to localStorage. Note: the app must define light and dark styles in your CSS, e.g., using Tailwind’s dark variant or your own classes.

TypeScript7/8/2025
#react#hooks#ui
TypeScript
import { useEffect, useState } from 'react';

export function useDarkMode() {
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    const root = window.document.documentElement;
    root.classList.remove(theme === 'light' ? 'dark' : 'light');
    root.classList.add(theme);
    localStorage.setItem('theme', theme);
  }, [theme]);

  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light');
  };

  return [theme, toggleTheme] as const;
}
...
Loading comments...