typescript

import { useCallback, useRef } from 'react';

const useDebounce = () => {
    const debounce = useRef<NodeJS.Timeout | null>(null);

    const clearDebounce = useCallback(() => {
        if (debounce.current) {
            clearTimeout(debounce.current);
        }
    }, []);

    const setDebounce = useCallback(
        (fn: () => void, time: number) => {
            clearDebounce();
            debounce.current = setTimeout(fn, time);
        },
        [clearDebounce]
    );

    return { setDebounce, clearDebounce };
};

export default useDebounce;