Last active
July 22, 2021 10:41
-
-
Save MauricioRobayo/36427e523d51f6c3159869291bf657d7 to your computer and use it in GitHub Desktop.
Custom react hook to get system color theme preference
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 { useEffect, useState } from "react"; | |
| const darkModeQuery = window.matchMedia("(prefers-color-scheme: dark)"); | |
| const usePrefersColorScheme = () => { | |
| const [colorScheme, setColorScheme] = useState<"dark" | "light">( | |
| darkModeQuery.matches ? "dark" : "light" | |
| ); | |
| useEffect(() => { | |
| const updateColorScheme = (event: MediaQueryListEvent) => { | |
| setColorScheme(event.matches ? "dark" : "light"); | |
| }; | |
| darkModeQuery.addEventListener("change", updateColorScheme); | |
| return () => { | |
| darkModeQuery.removeEventListener("change", updateColorScheme); | |
| }; | |
| }, []); | |
| return colorScheme; | |
| }; | |
| export default usePrefersColorScheme; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment