-
-
Save swyxio/dc6813be3d8ded7316d39757b4de87e2 to your computer and use it in GitHub Desktop.
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 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