import { useEffect, useMemo } from 'react'; import { useLocalStorage } from './useLocalStorage'; type Theme = 'light' | 'dark' | 'system'; export function useTheme() { const [theme, setTheme] = useLocalStorage('theme', 'system'); const systemTheme = useMemo(() => { if (typeof window !== 'undefined' && window.matchMedia) { return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } return 'light'; }, []); const applyTheme = () => { const themeToApply = theme === 'system' ? systemTheme : theme; const root = window.document.documentElement; root.classList.remove('light', 'dark'); root.classList.add(themeToApply); }; useEffect(() => { const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const handleChange = () => { if (theme === 'system') { applyTheme(); } }; mediaQuery.addEventListener('change', handleChange); return () => mediaQuery.removeEventListener('change', handleChange); // eslint-disable-next-line react-hooks/exhaustive-deps }, [theme]); useEffect(() => { applyTheme(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [theme, systemTheme]); return { theme, setTheme }; }