Skip to content

Instantly share code, notes, and snippets.

@stavros-melidoniotis
Created February 22, 2023 15:56
Show Gist options
  • Save stavros-melidoniotis/6fc8ebff3297d68a94f794598844dc09 to your computer and use it in GitHub Desktop.
Save stavros-melidoniotis/6fc8ebff3297d68a94f794598844dc09 to your computer and use it in GitHub Desktop.
React hook for easy retrieval of media dimensions
import { useState, useEffect } from "react";
const useMediaQuery = (query: string) => {
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