본문으로 건너뛰기

useDebounce

주어진 콜백 함수를 디바운스(지연) 처리하여 특정 시간 동안 반복 호출을 방지하는 훅입니다.


Code

🔗 실제 구현 코드 확인


Interface

typescript
type DebounceParameters = Parameters<typeof debounce>;

type DebounceReturnType<T extends (...args: any) => any> = ReturnType<
typeof debounce<T>
>;
typescript
function useDebounce<T extends (...args: any) => any>(
callback: T,
wait: DebounceParameters[1],
options?: DebounceParameters[2]
): DebounceReturnType<T>;

Parameters

NameTypeDescription
callbackT디바운스할 콜백 함수
waitnumber지연 시간(밀리초)
options{ maxWait?: number; leading?: boolean; trailing?: boolean; signal?: AbortSignal }디바운스 동작 옵션

Usage

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

const Example = () => {
const [count, setCount] = useState(1);
const [debouncedCount, setDebouncedCount] = useState(1);

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

const debouncedCountUp = useDebounce(() => {
setDebouncedCount(debouncedCount + 1);
}, 1000);

return (
<div>
<div style={{ display: "flex" }}>
<button onClick={countUp}>버튼 클릭</button>
<div style={{ width: "50px" }} />
<button onClick={debouncedCountUp}>debounce 버튼 클릭</button>
</div>
<div>
<p>count: {count}</p>
<p>debouncedCount: {debouncedCount}</p>
</div>
</div>
);
};

Example

count: 1

debouncedCount: 1