Last active
May 28, 2025 07:10
-
-
Save ZacharyBear/1c44237db76a7a3c02a6c45608613497 to your computer and use it in GitHub Desktop.
React dark mode hook
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 { useMemo, useSyncExternalStore } from 'React' | |
const useDark = () => { | |
const match = useMemo(() => window.matchMedia('(prefers-color-scheme: dark)'), []) | |
// Handlers | |
const subscribe = (cb: () => void) => { | |
match.addEventListener('change', cb) | |
return () => match.removeEventListener('change', cb) | |
} | |
// Syncs | |
const dark = useSyncExternalStore( | |
subscribe, | |
() => match.matches | |
) | |
return dark | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This hook could monitor the PC's color scheme responsive.
It queries
prefers-color-scheme
and follow it, updating while the OS has switched dark/light mode.Here is an use case: