Function: useThrottle()
@arolariu/components / useThrottle
Function: useThrottle()
useThrottle<
Args>(callback,delay): (...args) =>void
Defined in: hooks/useThrottle.tsx:40
Throttles a callback function, limiting how often it can be invoked.
Type Parameters
Args
Args extends unknown[]
The tuple type of the callback's arguments.
Parameters
callback
(...args) => void
The function to throttle.
delay
number
The minimum interval in milliseconds between invocations.
Returns
A throttled version of the callback.
(...args) => void
Remarks
This hook returns a throttled version of the provided callback that can only be executed once per specified interval. Subsequent calls within the interval are ignored. Useful for rate-limiting expensive operations triggered by high-frequency events like scrolling, resizing, or mouse movement.
Unlike debouncing, throttling ensures the callback is invoked at regular intervals during continuous events, providing more predictable execution timing.
Example
function ScrollTracker() {
const [scrollPos, setScrollPos] = useState(0);
const handleScroll = useThrottle(() => {
setScrollPos(window.scrollY);
}, 200);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [handleScroll]);
return <p>Scroll position: {scrollPos}</p>;
}