useThrottle
A React hook that creates a throttled version of a callback function. This is useful for limiting the rate at which a function can be called, such as when handling scroll or resize events.
Interface
ts
function useThrottle<F extends (...args: any[]) => any>(
callback: F,
wait: number,
options: { edges?: Array<'leading' | 'trailing'> }
): F & { cancel: () => void };
Parameters
- callbackrequired · F
The function to be throttled.
- waitrequired · number
The number of milliseconds to throttle invocations to.
- options{ edges?: Array<'leading' | 'trailing'> }
Options to control the behavior of the throttle.
- options.edgesArray<'leading' | 'trailing'> · ['leading', 'trailing']
An optional array specifying whether the function should be invoked on the leading edge, trailing edge, or both.
- options.edgesArray<'leading' | 'trailing'> · ['leading', 'trailing']
Return Value
- F & { cancel: () => void }
Returns the throttled function with a
cancel
method to cancel pending executions.
Example
tsx
const throttledScroll = useThrottle(
() => {
console.log('Scroll event');
},
200,
{ edges: ['leading', 'trailing'] }
);
useEffect(() => {
window.addEventListener('scroll', throttledScroll);
return () => {
window.removeEventListener('scroll', throttledScroll);
throttledScroll.cancel();
};
}, [throttledScroll]);