react-hooks-bank
Version:
A collection of **powerful, reusable custom React hooks** for complex, non-trivial interactions that go beyond React’s native features.
37 lines (36 loc) • 1.22 kB
JavaScript
import { useEffect, useState, useRef } from "react";
export function useThrottle(value, delay) {
var _a = useState(value), throttledValue = _a[0], setThrottledValue = _a[1];
var lastExecuted = useRef(0);
var timeout = useRef(null);
useEffect(function () {
var now = Date.now();
var remaining = delay - (now - lastExecuted.current);
if (remaining <= 0) {
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
}
setThrottledValue(value);
lastExecuted.current = now;
}
else {
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
}
timeout.current = setTimeout(function () {
setThrottledValue(value);
lastExecuted.current = Date.now();
timeout.current = null;
}, remaining);
}
return function () {
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
}
};
}, [value, delay]);
return throttledValue;
}