Created
April 15, 2025 07:01
-
-
Save imhalid/8e7d9c25a5dc0f0cbac5ff9fa6c4194a to your computer and use it in GitHub Desktop.
useMediaQuery.ts 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' | |
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