Skip to content

Instantly share code, notes, and snippets.

@schmidt1024
Created April 14, 2021 14:49
Show Gist options
  • Save schmidt1024/bc2f50303feca4bf71a1c7d9464ddfd0 to your computer and use it in GitHub Desktop.
Save schmidt1024/bc2f50303feca4bf71a1c7d9464ddfd0 to your computer and use it in GitHub Desktop.
custom react hook - get system prefered theme and use it
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