본문으로 건너뛰기

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

NameTypeDefaultDescription
callbackT-쓰로틀링할 콜백 함수
waitnumber-쓰로틀이 적용될 시간(밀리초)
options.signalAbortSignal-쓰로틀링된 함수를 취소하기 위한 AbortSignal
options.leadingbooleantrue첫 번째 호출을 실행할지 여부
options.trailingbooleantrue마지막 호출을 실행할지 여부

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