rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
37 lines (36 loc) • 1.6 kB
JavaScript
import { useEffect } from "react";
import { useFreshTick } from "./useFreshTick";
import { useIsomorphicEffect } from "./useIsomorphicEffect";
import { useRefElement } from "./useRefElement";
import { noop } from "../utils/noop";
/**
* useEventListenerRef hook
*
* A react hook to an event listener to an element
* Returns a ref
*
* @param {string} eventName The event to track`
* @param {Function} callback The callback to be called on event
* @param {object} listenerOptions The options to be passed to the event listener
* @param {boolean} isLayoutEffect Should it use layout effect. Defaults to false
* @returns {Function} A callback ref that can be used as ref prop
* @see https://react-hooks.org/docs/useEventListenerRef
*/
function useEventListenerRef(eventName, callback, listenerOptions, isLayoutEffect) {
if (listenerOptions === void 0) { listenerOptions = {}; }
if (isLayoutEffect === void 0) { isLayoutEffect = false; }
var _a = useRefElement(), ref = _a[0], element = _a[1];
var freshCallback = useFreshTick(callback);
var useEffectToRun = isLayoutEffect ? useIsomorphicEffect : useEffect;
useEffectToRun(function () {
if (!(element === null || element === void 0 ? void 0 : element.addEventListener)) {
return noop;
}
element.addEventListener(eventName, freshCallback, listenerOptions);
return function () {
element.removeEventListener(eventName, freshCallback, listenerOptions);
};
}, [element, eventName, listenerOptions]);
return ref;
}
export { useEventListenerRef };