import { useState, useEffect } from 'react'; /** * Hook for debouncing a value * * Returns a debounced version of the value that only updates after the * specified delay has passed without the value changing. * * @param value - Value to debounce * @param delay - Delay in milliseconds * @returns Debounced value * * @example * ```typescript * function SearchInput() { * const [searchTerm, setSearchTerm] = useState(''); * const debouncedSearchTerm = useDebounce(searchTerm, 500); * * useEffect(() => { * if (debouncedSearchTerm) { * // Perform search API call * searchAPI(debouncedSearchTerm); * } * }, [debouncedSearchTerm]); * * return ( * setSearchTerm(e.target.value)} * placeholder="Search..." * /> * ); * } * ``` */ export function useDebounce(value: T, delay: number = 500): T { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value); }, delay); return () => { clearTimeout(handler); }; }, [value, delay]); return debouncedValue; }