-
-
Save hunghg255/a2badbf2846461f972c8178f53e9bf2c 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