Created
December 23, 2020 10:57
-
-
Save anthowave/a136b79df4f998dc2fc8c3daaca41b62 to your computer and use it in GitHub Desktop.
A custom effect that updates the dark/light mode accordingly when the system setting gets changed
This file contains hidden or 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
const matchDark = '(prefers-color-scheme: dark)' | |
function useDarkMode() { | |
const [isDark, setIsDark] = React.useState( | |
() => window.matchMedia && window.matchMedia(matchDark).matches | |
); | |
React.useEffect(() => { | |
const matcher = window.matchMedia(matchDark); | |
const onChange = ({ matches }) => setIsDark(matches); | |
matcher.addEventListener(onChange); | |
return () => { | |
matcher.removeEventListener(onChange); | |
} | |
}, [setIsDark]); | |
return isDark; | |
} | |
// Thanks Tanner Linsley for this hook (https://www.youtube.com/watch?v=J-g9ZJha8FE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment