useThrottleCallback
Timing & asyncA powerful React hook for throttled callbacks with cancel, flush, and pending methods
Install
$ npm install @usefy/use-throttle-callbackQuick start
useThrottleCallback.tsx
import { useThrottleCallback } from "@usefy/use-throttle-callback";
function ScrollTracker() {
const handleScroll = useThrottleCallback(() => {
console.log("Scroll position:", window.scrollY);
}, 100);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
handleScroll.cancel();
window.removeEventListener("scroll", handleScroll);
};
}, [handleScroll]);
return <div>Scroll to see throttled logs</div>;
}API reference
useThrottleCallback<T>(callback, delay?, options?)
A hook that returns a throttled version of the provided callback function.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | T extends (...args: any[]) => any | — | The callback function to throttle |
delay | number | 500 | The throttle interval in milliseconds |
options | UseThrottleCallbackOptions | {} | Additional configuration options |
Options
| Option | Type | Default | Description |
|---|---|---|---|
leading | boolean | true | Invoke on the leading edge (first call) |
trailing | boolean | true | Invoke on the trailing edge (after interval) |
Returns ThrottledFunction<T>
| Property | Type | Description |
|---|---|---|
(...args) | ReturnType<T> | The throttled function (same signature as original) |
cancel | () => void | Cancels any pending invocation |
flush | () => ReturnType<T> | undefined | Immediately invokes any pending invocation and returns its result |
pending | () => boolean | Returns true if there's a pending invocation |
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.