UNPKG

@darwish/hooks-core

Version:

62 lines (61 loc) 2.54 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var useIsomorphicLayoutEffect_1 = __importDefault(require("./useIsomorphicLayoutEffect")); var IS_SERVER = typeof window === "undefined"; /** * Custom hook that tracks the state of a media query using the [`Match Media API`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia). * @param {string} query - The media query to track. * @param {?UseMediaQueryOptions} [options] - The options for customizing the behavior of the hook (optional). * @returns {boolean} The current state of the media query (true if the query matches, false otherwise). * @public * @example * ```tsx * const isSmallScreen = useMediaQuery('(max-width: 600px)'); * // Use `isSmallScreen` to conditionally apply styles or logic based on the screen size. * ``` */ function useMediaQuery(query, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.defaultValue, defaultValue = _c === void 0 ? false : _c, _d = _b.initializeWithValue, initializeWithValue = _d === void 0 ? true : _d; var getMatches = function (query) { if (IS_SERVER) { return defaultValue; } return window.matchMedia(query).matches; }; var _e = (0, react_1.useState)(function () { if (initializeWithValue) { return getMatches(query); } return defaultValue; }), matches = _e[0], setMatches = _e[1]; // Handles the change event of the media query. function handleChange() { setMatches(getMatches(query)); } (0, useIsomorphicLayoutEffect_1.default)(function () { var matchMedia = window.matchMedia(query); // Triggered at the first client-side load and if query changes handleChange(); // Use deprecated `addListener` and `removeListener` to support Safari < 14 (#135) if (matchMedia.addListener) { matchMedia.addListener(handleChange); } else { matchMedia.addEventListener("change", handleChange); } return function () { if (matchMedia.removeListener) { matchMedia.removeListener(handleChange); } else { matchMedia.removeEventListener("change", handleChange); } }; }, [query]); return matches; } exports.default = useMediaQuery;