Skip to content

Instantly share code, notes, and snippets.

@enpitsuLin
Created August 27, 2022 05:51
Show Gist options
  • Save enpitsuLin/75dc9cf74b6937002881e18f3947063e to your computer and use it in GitHub Desktop.
Save enpitsuLin/75dc9cf74b6937002881e18f3947063e to your computer and use it in GitHub Desktop.
type Theme = 'system' | 'dark' | 'light'
export default function useTheme() {
const [theme, setTheme] = useState<Theme>(() => {
if (typeof localStorage === 'undefined') return 'system'
return (localStorage.getItem('theme') as Theme) || 'system'
})
useEffect(() => {
const root = document.documentElement
if (theme === 'system') {
localStorage.removeItem('theme')
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
root.classList.add('dark')
} else {
root.classList.remove('dark')
}
} else {
localStorage.setItem('theme', theme)
if (theme === 'light') {
root.classList.remove('dark')
} else {
root.classList.add('dark')
}
}
}, [theme])
return { theme, setTheme }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment