import { useEffect, useRef, useState } from "react";

const useDebounce = <T>(value: T, delay = 500) => {
	const [returnValue, setValue] = useState<T>(value);
	const timer = useRef<NodeJS.Timeout | undefined>(undefined);

	useEffect(() => {
		if (timer.current) clearTimeout(timer.current);

		timer.current = setTimeout(() => {
			setValue(value);
		}, delay);

		return () => {
			if (timer.current) clearTimeout(timer.current);
		};
	}, [delay, value]);

	return returnValue;
};

export default useDebounce;
