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.

Revisions

  1. davidmc971 created this gist Nov 23, 2022.
    24 changes: 24 additions & 0 deletions useMediaQuery.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    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;