UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

30 lines (29 loc) 1.17 kB
import { useEffect, useMemo, useState } from "react"; /** * useMediaMatch * * A react hook that signals whether or not a media query is matched. * * @param query The media query to signal on. Example, `"print"` will signal * `true` when previewing in print mode, and `false` otherwise. * @returns Whether or not the media query is currently matched. * @see https://react-hooks.org/docs/useMediaMatch */ function useMediaMatch(query) { var matchMedia = useMemo(function () { return window.matchMedia(query); }, [query]); var _a = useState(function () { return matchMedia.matches; }), matches = _a[0], setMatches = _a[1]; useEffect(function () { setMatches(matchMedia.matches); var listener = function (event) { return setMatches(event.matches); }; matchMedia.addEventListener("change", listener); return function () { return matchMedia.removeEventListener("change", listener); }; }, [matchMedia]); if (typeof window === "undefined") { console.warn("useMediaMatch cannot function as window is undefined."); return false; } return matches; } export { useMediaMatch };