UNPKG

@fe-fast/code-sweeper

Version:

A lightweight JavaScript/TypeScript code cleaning tool

29 lines (24 loc) 744 B
import { useState, useEffect } from 'react'; type Theme = 'light' | 'dark'; export function useTheme() { const [theme, setTheme] = useState<Theme>(() => { const savedTheme = localStorage.getItem('theme') as Theme; if (savedTheme) { return savedTheme; } return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; }); useEffect(() => { document.documentElement.classList.remove('light', 'dark'); document.documentElement.classList.add(theme); localStorage.setItem('theme', theme); }, [theme]); const toggleTheme = () => { setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light'); }; return { theme, toggleTheme, isDark: theme === 'dark' }; }