Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created September 2, 2020 18:08
Show Gist options
  • Save mjackson/05673df9963dd18a7ef6ccc035f07cf0 to your computer and use it in GitHub Desktop.
Save mjackson/05673df9963dd18a7ef6ccc035f07cf0 to your computer and use it in GitHub Desktop.
import React from "react";
export type ColorScheme = "light" | "dark";
export default function useColorSchemePreference(
defaultColorScheme: ColorScheme = "light"
) {
let darkQuery = "(prefers-color-scheme: dark)";
let [colorScheme, setColorScheme] = React.useState<ColorScheme>(
typeof window === "object" && window.matchMedia
? window.matchMedia(darkQuery).matches
? "dark"
: "light"
: defaultColorScheme
);
React.useEffect(() => {
function handleChange(event: MediaQueryListEvent) {
setColorScheme(event.matches ? "dark" : "light");
}
if (window.matchMedia) {
let mql = window.matchMedia(darkQuery);
mql.addEventListener("change", handleChange);
return () => {
mql.removeEventListener("change", handleChange);
};
}
}, []);
return colorScheme;
}
// Use it like:
let colorScheme: ColorScheme = useColorSchemePreference();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment