import { useEffect, useState } from "react";

function useDebounce<T>(
    value: T,
    delay: number,
    callback: (debouncedValue: T) => void,
    changed?: (changedValue: T) => void,
) {
    const [debounce, setDebounce] = useState(value);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebounce(value);
        }, delay);

        changed?.(value);

        return () => {
            clearTimeout(handler);
        };
    }, [value]);

    useEffect(() => {
        callback(debounce);
    }, [debounce]);

    return debounce;
}

export { useDebounce };
