Skip to main content

useDebounce

debounce를 쉽게 사용할 수 있는 커스텀 훅입니다.


Code

🔗 실제 구현 코드 확인

Interface

typescript
// lodash-es DebounceSettings
// https://www.geeksforgeeks.org/lodash-_-debounce-method/
interface DebounceSettings {
leading?: boolean | undefined;
maxWait?: number | undefined;
trailing?: boolean | undefined;
}

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

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