Created
November 27, 2019 06:12
-
-
Save knjname/b8f6826ca5915e430bc99139a9663f85 to your computer and use it in GitHub Desktop.
A react hook for DarkMode detection.
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
import { useEffect, useState } from "react"; | |
const darkModeQuery = matchMedia("(prefers-color-scheme: dark)"); | |
export const useDarkMode = () => { | |
const [isDark, setDark] = useState(darkModeQuery.matches); | |
useEffect(() => { | |
const listener = () => { | |
console.log("Dark mode changed", darkModeQuery.matches); | |
setDark(darkModeQuery.matches); | |
}; | |
darkModeQuery.addListener(listener); | |
return () => { | |
darkModeQuery.removeListener(listener); | |
}; | |
}); | |
return isDark; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment