Created
April 14, 2021 14:49
-
-
Save cod3cow/bc2f50303feca4bf71a1c7d9464ddfd0 to your computer and use it in GitHub Desktop.
custom react hook - get system prefered theme and use it
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.addListener(onChange) | |
return () => { | |
matcher.removeListiner(onChange) | |
} | |
}, [setIsDark]) | |
return isDark | |
} | |
// import useDarkMode from './useDarkMode' | |
// | |
// function App() { | |
// const theme = useDarkMode() | |
// ? themes.dark | |
// : themes.light | |
// | |
// return ( | |
// <ThemeProvider theme={theme}> | |
// ... | |
// </ThemeProvider> | |
// ) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment