Created
August 27, 2022 05:51
-
-
Save enpitsuLin/75dc9cf74b6937002881e18f3947063e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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