useThrottle
A hook that applies throttling to the given callback function for a specified duration to prevent repeated calls within that time window.
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
| Name | Type | Default | Description |
|---|---|---|---|
callback | T | - | The callback function to throttle |
wait | number | - | The throttle duration in milliseconds |
options.signal | AbortSignal | - | An optional AbortSignal to cancel the throttled function |
options.leading | boolean | true | Whether to execute on the leading edge |
options.trailing | boolean | true | Whether 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