useDebounce
debounce
를 쉽게 사용할 수 있는 커스텀 훅입니다.
Interface
// 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>;
const useDebounce: (
callback: DebounceParameters[0], // (...args: any) => any
wait: DebounceParameters[1], // number
options?: DebounceParameters[2] // DebounceSettings
) => DebouncedFunc<(...args: any) => any>;
Usage
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 countUpWithDebounce = useDebounce(() => {
setDebouncedCount(debouncedCount + 1);
}, 1000);
return (
<div>
<div style={{ display: "flex" }}>
<button onClick={countUp}>버튼 클릭</button>
<div style={{ width: "50px" }} />
<button onClick={countUpWithDebounce}>debounce 버튼 클릭</button>
</div>
<div>
<p>count: {count}</p>
<p>debouncedCount: {debouncedCount}</p>
</div>
</div>
);
};
Example
count: 1
debouncedCount: 1