Created
March 14, 2023 13:39
-
-
Save awareness481/b8a0cd4e6d4b6a3f02f3aa9f3cc47e56 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
// only works on react 18 | |
import { useSyncExternalStore } from "react"; | |
export const useColorScheme = () => { | |
const scheme = useSyncExternalStore( | |
subscribe, | |
getSnapshot, | |
getServerSnapshot | |
); | |
return scheme; | |
}; | |
function getServerSnapshot() { | |
return "no-preference"; | |
} | |
function getSnapshot() { | |
if (window.matchMedia("(prefers-color-scheme: dark)").matches) { | |
return "dark"; | |
} | |
if (window.matchMedia("(prefers-color-scheme: light)").matches) { | |
return "light"; | |
} | |
return "no-preference"; | |
} | |
function subscribe(callback: (callback: MediaQueryListEvent) => unknown) { | |
const isDark = window.matchMedia("(prefers-color-scheme: dark)"); | |
const isLight = window.matchMedia("(prefers-color-scheme: light)"); | |
isDark.addEventListener("change", callback); | |
isLight.addEventListener("change", callback); | |
return () => { | |
isDark.removeEventListener("change", callback); | |
isLight.removeEventListener("change", callback); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment