Skip to content

Instantly share code, notes, and snippets.

@cassidoo
Last active October 27, 2022 16:13
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cassidoo/83e92e33cd09063c799a98199bb2ad75 to your computer and use it in GitHub Desktop.
Save cassidoo/83e92e33cd09063c799a98199bb2ad75 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>)
}
// Same thing as the other one, but more server-friendly instead of SPA stuff
function useMedia(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => {
setMatches(media.matches);
};
media.addEventListener("change", listener);
return () => media.removeEventListener("change", listener);
}, [matches, query]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment