Created
September 2, 2020 18:08
-
-
Save mjackson/05673df9963dd18a7ef6ccc035f07cf0 to your computer and use it in GitHub Desktop.
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 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