useThrottle
주어진 콜백 함수를 지정된 시간 동안 쓰로틀링 처리하여 특정 시간 동안 반복 호출을 방지하는 훅입니다.
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 | - | 쓰로틀링할 콜백 함수 |
wait | number | - | 쓰로틀이 적용될 시간(밀리초) |
options.signal | AbortSignal | - | 쓰로틀링된 함수를 취소하기 위한 AbortSignal |
options.leading | boolean | true | 첫 번째 호출을 실행할지 여부 |
options.trailing | boolean | true | 마지막 호출을 실행할지 여부 |
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}>버튼 클릭</button>
<div style={{ width: "50px" }} />
<button onClick={throttledCountUp}>throttle 버튼 클릭</button>
</div>
<div>
<p>count: {count}</p>
<p>throttledCount: {throttledCount}</p>
</div>
</div>
);
};
Example
count: 1
throttledCount: 1