UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

24 lines 1.2 kB
import { useEffect, useRef } from 'react'; import { useEventListener } from './useEventListener'; import { useThrottledCallback } from '../performance-optimization/useThrottledCallback'; /** * Attaches an event listener to a target element but throttles the callback execution. * * @param eventName The name of the event to listen for (e.g., 'scroll', 'resize'). * @param handler The function to execute when the event occurs. * @param delay The throttle delay in milliseconds. * @param element The target element or ref to attach the listener to (compatible with useEventListener). * @param options Event listener options (capture, passive, once). */ export function useThrottledEventListener(eventName, handler, delay, element, options) { const savedHandler = useRef(handler); useEffect(() => { savedHandler.current = handler; }, [handler]); const throttledCallback = useThrottledCallback((event) => { var _a; (_a = savedHandler.current) === null || _a === void 0 ? void 0 : _a.call(savedHandler, event); }, [], delay); useEventListener(eventName, throttledCallback, element, options); } //# sourceMappingURL=useThrottledEventListener.js.map