Skip to main content

useThrottle

useThrottle.tsx
import { useState, useEffect } from "react";

function useThrottle(value: any, delay: number): any {
const [throttledValue, setThrottledValue] = useState(value);
const [lastExecuted, setLastExecuted] = useState(Date.now());

useEffect(() => {
const now = Date.now();
const timeSinceLastExecuted = now - lastExecuted;

if (timeSinceLastExecuted >= delay) {
setThrottledValue(value);
setLastExecuted(now);
} else {
const timeoutId = setTimeout(() => {
setThrottledValue(value);
setLastExecuted(Date.now());
}, delay - timeSinceLastExecuted);

return () => {
clearTimeout(timeoutId);
};
}
}, [value, delay, lastExecuted]);

return throttledValue;
}