import { useState, useEffect } from 'react'; function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { // Update debounced value after delay const handler = setTimeout(() => { setDebouncedValue(value); }, delay); // Cancel the timeout if value changes (or component unmounts) // This is important for preventing debouncedValue from being updated // to a stale value if the original value changes rapidly. return () => { clearTimeout(handler); }; }, [value, delay]); // Only re-call effect if value or delay changes return debouncedValue; } // Example Usage: // function SearchInput() { // const [searchTerm, setSearchTerm] = useState(''); // const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay // useEffect(() => { // if (debouncedSearchTerm) { // console.log('Fetching data for:', debouncedSearchTerm); // // In a real app, you would fetch data here // } // }, [debouncedSearchTerm]); // return ( // setSearchTerm(e.target.value)} // /> // ); // }