Skip to main content

useThrottle

주어진 콜백 함수를 지정된 시간 동안 쓰로틀링 처리하여 특정 시간 동안 반복 호출을 방지하는 훅입니다.


Code

🔗 실제 구현 코드 확인

Interface

typescript
/**
* @interface ThrottleParameters
* @template T - 콜백 함수 타입입니다.
* @param {ThrottleParameters[0]} callback - 스로틀링할 콜백 함수입니다.
* @param {ThrottleParameters[1]} wait - 스로틀링 시간(밀리초)입니다.
* @param {ThrottleParameters[2]} options - 옵션 객체입니다.
* @param {AbortSignal} options.signal - 스로틀링된 함수를 취소하기 위한 선택적 AbortSignal입니다.
* @param {boolean} options.leading - 첫 번째 호출을 실행할지 여부입니다.
* @param {boolean} options.trailing - 마지막 호출을 실행할지 여부입니다.
*/
type ThrottleParameters = Parameters<typeof throttle>;

/**
* @interface ThrottleReturnType
* @template T - 콜백 함수 타입입니다.
* @param {() => void} cancel - 스로틀링된 함수의 대기 중인 실행을 취소합니다.
* @param {() => void} flush - 대기 중인 실행이 있는 경우 스로틀링된 함수를 즉시 실행합니다.
*/
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>;

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