useMediaQuery()
Easily retrieve media dimensions with this Hook React which also works onResize.
Note:
Before Safari 14, MediaQueryList
is based on EventTarget
and only supports addListener
/removeListener
for media queries. If you don't support these versions you may remove these checks. Read more about this on MDN.
The Hook
1import { useEffect, useState } from 'react'23function useMediaQuery(query: string): boolean {4 const getMatches = (query: string): boolean => {5 // Prevents SSR issues6 if (typeof window !== 'undefined') {7 return window.matchMedia(query).matches8 }9 return false10 }1112 const [matches, setMatches] = useState<boolean>(getMatches(query))1314 function handleChange() {15 setMatches(getMatches(query))16 }1718 useEffect(() => {19 const matchMedia = window.matchMedia(query)2021 // Triggered at the first client-side load and if query changes22 handleChange()2324 // Listen matchMedia25 if (matchMedia.addListener) {26 matchMedia.addListener(handleChange)27 } else {28 matchMedia.addEventListener('change', handleChange)29 }3031 return () => {32 if (matchMedia.removeListener) {33 matchMedia.removeListener(handleChange)34 } else {35 matchMedia.removeEventListener('change', handleChange)36 }37 }38 // eslint-disable-next-line react-hooks/exhaustive-deps39 }, [query])4041 return matches42}4344export default useMediaQuery
Usage
1import { useMediaQuery } from 'usehooks-ts'23export default function Component() {4 const matches = useMediaQuery('(min-width: 768px)')56 return (7 <div>8 {`The view port is ${matches ? 'at least' : 'less than'} 768 pixels wide`}9 </div>10 )11}
See a way to make this page better?
Edit there »