import { useRef, useEffect } from 'react'; /** * Custom hook to debounce a function. * @param callback The function to debounce. * @param delay The delay time in milliseconds. * @returns A debounced version of the provided function. */ export function useDebounce(callback: (...args: T) => void, delay: number) { const timeoutRef = useRef | null>(null); const callbackRef = useRef<(...args: T) => void>(callback); const isMountedRef = useRef(true); useEffect(() => { callbackRef.current = callback; }, [callback]) useEffect(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; if (timeoutRef.current) { clearTimeout(timeoutRef.current); } } }, []) const debounced = (...args: T) => { if (timeoutRef.current) { clearTimeout(timeoutRef.current) } timeoutRef.current = setTimeout(() => { if (isMountedRef.current) { callbackRef.current(...args) } }, delay); } return debounced; }