Skip to main content

useThrottle

A hook that applies throttling to the given callback function for a specified duration to prevent repeated calls within that time window.


Code

🔗 View source code


Interface

typescript
type ThrottleParameters = Parameters<typeof throttle>;

type ThrottleReturnType<T extends (...args: any) => any> = ReturnType<
typeof throttle<T>
>;
typescript
function useThrottle<T extends (...args: any) => any>(
callback: T,
wait: ThrottleParameters[1],
options?: ThrottleParameters[2]
): ThrottleReturnType<T>;

Options

NameTypeDefaultDescription
callbackT-The callback function to throttle
waitnumber-The throttle duration in milliseconds
options.signalAbortSignal-An optional AbortSignal to cancel the throttled function
options.leadingbooleantrueWhether to execute on the leading edge
options.trailingbooleantrueWhether to execute on the trailing edge

Usage

typescript
import { useState } from 'react';
import { useThrottle } from '@modern-kit/react';

const Example = () => {
const [count, setCount] = useState(1);
const [throttledCount, setThrottledCount] = useState(1);

const countUp = () => {
setCount(count + 1);
};

const throttledCountUp = useThrottle(() => {
setThrottledCount(throttledCount + 1);
}, 1000);

return (
<div>
<div style={{ display: "flex" }}>
<button onClick={countUp}>Click Button</button>
<div style={{ width: "50px" }} />
<button onClick={throttledCountUp}>Click Throttled Button</button>
</div>
<div>
<p>count: {count}</p>
<p>throttledCount: {throttledCount}</p>
</div>
</div>
);
};

Example

count: 1

throttledCount: 1