@react-md/utils
Version:
General utils for react-md.
67 lines • 2.59 kB
JavaScript
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { useEffect, useState } from "react";
/**
* A helper hook that is used to create a memoized media query tester for
* `window.matchMedia`.
*
* Note: This is a **client side only** hook as it requires the `window` to
* attach a resize event listener to.
*
* @param query - The media query to use
* @param defaultValue - The default value for if this media query matches. When
* this is `undefined`, it will default to `false` unless the `window` is
* defined and the `checkImmediately` param was not set to `false`. Otherwise,
* it will check the media query matches on mount and use that value.
* @param disabled - Boolean if the media query checking should be disabled.
* @param checkImmediately - Boolean if the media query should be checked
* immediately on mount. When omitted, it will default to checking when the
* window is defined.
* @returns true if the media query is a match.
*/
export function useMediaQuery(query, defaultValue, disabled, checkImmediately) {
if (disabled === void 0) { disabled = false; }
if (checkImmediately === void 0) { checkImmediately = typeof window !== "undefined"; }
var _a = __read(useState(function () {
if (typeof defaultValue !== "undefined") {
return defaultValue;
}
if (!disabled && checkImmediately && typeof window !== "undefined") {
return window.matchMedia(query).matches;
}
return false;
}), 2), matches = _a[0], setMatches = _a[1];
useEffect(function () {
if (typeof window === "undefined" || disabled) {
return;
}
var mq = window.matchMedia(query);
var updater = function (_a) {
var matches = _a.matches;
return setMatches(matches);
};
mq.addEventListener("change", updater);
if (mq.matches !== matches) {
setMatches(mq.matches);
}
return function () {
mq.removeEventListener("change", updater);
};
}, [disabled, matches, query]);
return matches;
}
//# sourceMappingURL=useMediaQuery.js.map