Skip to content

Instantly share code, notes, and snippets.

@imhalid
Created April 15, 2025 07:01
Show Gist options
  • Save imhalid/8e7d9c25a5dc0f0cbac5ff9fa6c4194a to your computer and use it in GitHub Desktop.
Save imhalid/8e7d9c25a5dc0f0cbac5ff9fa6c4194a to your computer and use it in GitHub Desktop.
useMediaQuery.ts hook
import { useMemo, useSyncExternalStore } from 'react'
export function useMediaQuery(query: string): boolean {
const isClient = typeof window !== 'undefined'
const media = useMemo(() => (isClient ? window.matchMedia(query) : null), [query])
return useSyncExternalStore(
(callback) => {
if (media) {
media.addEventListener('change', callback)
return () => media.removeEventListener('change', callback)
}
return () => {}
},
() => (media ? media.matches : false),
() => false
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment