import { useState, useEffect } from 'react'; function useDebounce(value, delay) { const [debouncedValue, setDebouncedValue] = useState(value); useEffect(() => { // Set debouncedValue to value (passed in) after the specified delay const handler = setTimeout(() => { setDebouncedValue(value); }, delay); // Return a cleanup function that will be called every time useEffect is re-executed // or when the component unmounts. This clears the timeout if value changes // before the delay has passed, ensuring only the last value is debounced. return () => { clearTimeout(handler); }; }, [value, delay]); // Only re-call effect if value or delay changes return debouncedValue; } // Usage example: // function SearchInput() { // const [searchTerm, setSearchTerm] = useState(''); // const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms debounce // useEffect(() => { // if (debouncedSearchTerm) { // console.log('Fetching data for:', debouncedSearchTerm); // // Perform API call or heavy computation here // } // }, [debouncedSearchTerm]); // return ( // setSearchTerm(e.target.value)} // /> // ); // }