Skip to content

Instantly share code, notes, and snippets.

@anthowave
Created December 23, 2020 10:57
Show Gist options
  • Save anthowave/a136b79df4f998dc2fc8c3daaca41b62 to your computer and use it in GitHub Desktop.
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
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