UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

36 lines (35 loc) 1.76 kB
import { useEffect } from "react"; import { useFreshTick } from "./useFreshTick"; import { useIsomorphicEffect } from "./useIsomorphicEffect"; import { warning } from "./warning"; /** * useGlobalObjectEventListener hook * * A react hook to an event listener to a global object * * @param {Window|Document} globalObject The global object to add event onto * @param {string} eventName The event to track * @param {Function} callback The callback to be called on event * @param {ListenerOptions} listenerOptions The options to be passed to the event listener * @param {boolean} when Should the event listener be active * @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false * @see https://react-hooks.org/docs/useGlobalObjectEventListener */ function useGlobalObjectEventListener(globalObject, eventName, callback, listenerOptions, when, isLayoutEffect) { if (listenerOptions === void 0) { listenerOptions = {}; } if (when === void 0) { when = true; } if (isLayoutEffect === void 0) { isLayoutEffect = false; } var freshCallback = useFreshTick(callback); var useEffectToRun = isLayoutEffect ? useIsomorphicEffect : useEffect; useEffectToRun(function () { warning(typeof globalObject !== "undefined", "[useGlobalObjectEventListener]: Cannot attach event handlers to undefined."); if (typeof globalObject !== "undefined" && when) { globalObject.addEventListener(eventName, freshCallback, listenerOptions); return function () { globalObject.removeEventListener(eventName, freshCallback, listenerOptions); }; } return function () { }; }, [eventName, listenerOptions]); } export { useGlobalObjectEventListener };