Skip to content

Instantly share code, notes, and snippets.

@aggutierrez98
Forked from cassidoo/useMedia.jsx
Created May 1, 2022 03:56
Show Gist options
  • Save aggutierrez98/02cc539baeb6a3f7fbd7bb9d759bc0c1 to your computer and use it in GitHub Desktop.
Save aggutierrez98/02cc539baeb6a3f7fbd7bb9d759bc0c1 to your computer and use it in GitHub Desktop.
An example of checking on a media query with React Hooks
function useMedia(query) {
const [matches, setMatches] = useState(window.matchMedia(query).matches)
useEffect(() => {
const media = window.matchMedia(query)
if (media.matches !== matches) {
setMatches(media.matches)
}
const listener = () => {
setMatches(media.matches)
}
media.addEventListener(listener)
return () => media.removeEventListener(listener)
}, [matches, query])
return matches
}
// Example usage:
function SomeComponent() {
let isWide = useMedia('(min-width: 800px)')
return (<div>The window is {isWide ? 'wide' : 'not wide'}</div>)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment