Created
November 23, 2022 17:59
-
-
Save davidmc971/da8429d6876418539447508b2351d4c5 to your computer and use it in GitHub Desktop.
Revisions
-
davidmc971 created this gist
Nov 23, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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;