Skip to content

Instantly share code, notes, and snippets.

@mmaous
Created May 17, 2022 15:01
Show Gist options
  • Save mmaous/df5dbfea78a6182b6bb989eb0ce46e49 to your computer and use it in GitHub Desktop.
Save mmaous/df5dbfea78a6182b6bb989eb0ce46e49 to your computer and use it in GitHub Desktop.
Easily retrieve media dimensions with this Hook React which also works onResize.
import { useState, useEffect } from "react";
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
window.addEventListener("resize", listener);
return () => window.removeEventListener("resize", listener);
}, [matches, query]);
return matches;
}
export default useMediaQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment