UNPKG

hooks-belt

Version:

A comprehensive collection of useful React hooks for common use cases

47 lines 1.51 kB
import { useCallback, useRef } from 'react'; /** * A hook that throttles a function execution. * Ensures the function is called at most once in a specified time period. * * @param func - The function to throttle * @param delay - The throttle delay in milliseconds * @returns A throttled version of the function * * @example * ```tsx * const throttledScrollHandler = useThrottle(() => { * console.log('Scroll event throttled') * }, 100) * * useEffect(() => { * window.addEventListener('scroll', throttledScrollHandler) * return () => window.removeEventListener('scroll', throttledScrollHandler) * }, [throttledScrollHandler]) * ``` */ export function useThrottle(func, delay) { const lastExecuted = useRef(0); const timeoutId = useRef(undefined); return useCallback(((...args) => { const now = Date.now(); if (now - lastExecuted.current >= delay) { ; func(...args); lastExecuted.current = now; } else { // Clear existing timeout if (timeoutId.current) { clearTimeout(timeoutId.current); } // Set new timeout const remainingDelay = delay - (now - lastExecuted.current); timeoutId.current = setTimeout(() => { ; func(...args); lastExecuted.current = Date.now(); }, remainingDelay); } }), [func, delay]); } //# sourceMappingURL=useThrottle.js.map