Skip to content

Instantly share code, notes, and snippets.

@ZacharyBear
Last active May 28, 2025 07:10
Show Gist options
  • Save ZacharyBear/1c44237db76a7a3c02a6c45608613497 to your computer and use it in GitHub Desktop.
Save ZacharyBear/1c44237db76a7a3c02a6c45608613497 to your computer and use it in GitHub Desktop.
React dark mode hook
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
}
@ZacharyBear
Copy link
Author

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:

const DarkSwitch = () => {
  // Hooks
  const systemDark = useDark()
  const [value, setValue] = useState(systemDark)

  // Sync while External dark mode changed
  useEffect(() => {
    setValue(systemDark)
  }, [systemDark])

  return <span>{value ? '🌑' : '☀️'}</span>
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment