Last active
October 12, 2023 16:23
-
-
Save tvler/7f9b47ba5cbcbac428403eba97b24268 to your computer and use it in GitHub Desktop.
useSystemTheme.ts
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 * as React from "react"; | |
function getMediaQuery(): MediaQueryList { | |
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); | |
return mediaQuery; | |
} | |
function subscribe(onStoreChange: () => void): () => void { | |
const mediaQuery = getMediaQuery(); | |
mediaQuery.addEventListener("change", onStoreChange); | |
return () => { | |
mediaQuery.removeEventListener("change", onStoreChange); | |
}; | |
} | |
function getSnapshot(): boolean { | |
const mediaQuery = getMediaQuery(); | |
return mediaQuery.matches; | |
} | |
export function useSystemTheme(): "dark" | "light" { | |
return React.useSyncExternalStore(subscribe, getSnapshot) ? "dark" : "light"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment