Created
August 24, 2021 08:56
-
-
Save tomaswrobel/42c748cdc266451f6c6e8eb6b941f7ab to your computer and use it in GitHub Desktop.
useDarkScheme React hook – simple hook for detecting dark scheme in native settings
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
import {useState, useEffect, useRef} from "react" | |
export default function () { | |
const {current} = useRef(matchMedia("(prefers-color-scheme: dark)")); | |
const [match, setMatches] = useState(current.matches); | |
useEffect(() => { | |
const updateMatch = () => { | |
setMatch(current.matches); | |
}; | |
current.addEventListener( | |
"change", updateMatch | |
); | |
return () => { | |
current.removeEventListener( | |
"change", | |
updateMatch | |
); | |
}; | |
}, []); | |
return match; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment