@darwish/hooks-core
Version:
56 lines (55 loc) • 2.26 kB
JavaScript
import { useState } from "react";
import useIsomorphicLayoutEffect from "./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.
* ```
*/
export default 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 = 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));
}
useIsomorphicLayoutEffect(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;
}