created at 2023/06/01 12:57:08
updated at 2023/06/01 12:57:15
TypeScript
import { useEffect } from "react";
import usePrefersDarkMode from "./usePrefersDarkMode";
import { useSafeLocalStorage } from "./useSafeLocalStorage";
export function useDarkMode(isDark: boolean) {
const prefersDarkMode = usePrefersDarkMode(isDark);
const [isEnabled, setIsEnabled] = useSafeLocalStorage("dark-mode", isDark);
const enabled = isEnabled === undefined ? prefersDarkMode : isEnabled;
useEffect(() => {
if (window === undefined) return;
const root = window.document.documentElement;
root.classList.remove(enabled ? "light" : "dark");
root.classList.add(enabled ? "dark" : "light");
}, [enabled]);
return [enabled, setIsEnabled];
}