Dark mode using CSS custom properties for easy theming.
CSS:
1:root {2 --bg-primary: #ffffff;3 --bg-secondary: #f5f5f5;4 --text-primary: #000000;5 --text-secondary: #666666;6 --border-color: #e0e0e0;7}89.dark {10 --bg-primary: #1a1a1a;11 --bg-secondary: #2a2a2a;12 --text-primary: #ffffff;13 --text-secondary: #aaaaaa;14 --border-color: #404040;15}1617body {18 background-color: var(--bg-primary);19 color: var(--text-primary);20}
React hook:
1function useTheme() {2 const [theme, setTheme] = useState(() => {3 if (typeof window !== "undefined") {4 return localStorage.getItem("theme") || "system";5 }6 return "system";7 });89 useEffect(() => {10 const root = document.documentElement;1112 if (theme === "system") {13 const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;14 root.classList.toggle("dark", prefersDark);15 } else {16 root.classList.toggle("dark", theme === "dark");17 }1819 localStorage.setItem("theme", theme);20 }, [theme]);2122 return { theme, setTheme };23}2425// Usage26function ThemeToggle() {27 const { theme, setTheme } = useTheme();2829 return (30 <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>31 {theme === "dark" ? "Light" : "Dark"}32 </button>33 );34}
Benefits: