Skip to content

Instantly share code, notes, and snippets.

@tomas-wrobel
Created August 24, 2021 08:56
Show Gist options
  • Save tomas-wrobel/42c748cdc266451f6c6e8eb6b941f7ab to your computer and use it in GitHub Desktop.
Save tomas-wrobel/42c748cdc266451f6c6e8eb6b941f7ab to your computer and use it in GitHub Desktop.
useDarkScheme React hook – simple hook for detecting dark scheme in native settings
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