@ehsaneha/react-throttle
Version:
useThrottle is a custom React hook that limits how often a function can be called by ensuring it's invoked at most once within a specified delay period.
40 lines (39 loc) • 1.26 kB
JavaScript
import { useRef, useEffect, useCallback } from "react";
/**
* useThrottle
* @param callback - Function to be throttled
* @param delay - Time interval in milliseconds
*/
export function useThrottle(callback, delay) {
const lastCall = useRef(0);
const timeout = useRef(null);
const savedCallback = useRef(callback);
// Update ref if callback changes
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
const throttled = useCallback((...args) => {
const now = Date.now();
if (now - lastCall.current >= delay) {
lastCall.current = now;
savedCallback.current(...args);
}
//
else if (!timeout.current) {
const remaining = delay - (now - lastCall.current);
timeout.current = setTimeout(() => {
lastCall.current = Date.now();
timeout.current = null;
savedCallback.current(...args);
}, remaining);
}
}, [delay]);
// Cleanup on unmount
useEffect(() => {
return () => {
if (timeout.current)
clearTimeout(timeout.current);
};
}, []);
return throttled;
}