Skip to content

Instantly share code, notes, and snippets.

@davidmc971
Created November 23, 2022 17:59
Show Gist options
  • Select an option

  • Save davidmc971/da8429d6876418539447508b2351d4c5 to your computer and use it in GitHub Desktop.

Select an option

Save davidmc971/da8429d6876418539447508b2351d4c5 to your computer and use it in GitHub Desktop.
Custom media query hook in React
import { useEffect, useRef, useState } from "react";
const useMediaQuery = (minWidth, maxWidth) => {
const mediaQuery = "screen".concat(
minWidth !== undefined ? ` and (min-width: ${minWidth})` : "",
maxWidth !== undefined ? ` and (max-width: ${maxWidth})` : ""
);
const [matches, setMatches] = useState(window.matchMedia(mediaQuery).matches);
const listenerAdded = useRef(false);
useEffect(() => {
if (listenerAdded.current) return;
window
.matchMedia(mediaQuery)
.addEventListener("change", (e) => setMatches(e.matches));
listenerAdded.current = true;
}, [mediaQuery]);
return matches;
};
export default useMediaQuery;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment