Skip to content

Instantly share code, notes, and snippets.

@hunghg255
Forked from awareness481/useColorScheme.ts
Created November 3, 2023 17:16
Show Gist options
  • Save hunghg255/a2badbf2846461f972c8178f53e9bf2c to your computer and use it in GitHub Desktop.
Save hunghg255/a2badbf2846461f972c8178f53e9bf2c to your computer and use it in GitHub Desktop.
// 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