JAVASCRIPT
React `useDebounce` Hook for Input Throttling
Implement a custom React `useDebounce` hook to delay execution of a function until a certain time has passed without further calls, optimizing performance for search inputs and API requests.
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
// Example Usage:
// function SearchComponent() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Fetching data for:', debouncedSearchTerm);
// // Perform API call or heavy computation here
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This `useDebounce` hook delays updating a value until a specified `delay` has passed since the last change. It's perfect for optimizing performance by preventing frequent re-renders or API calls when a user is typing rapidly into an input field, ensuring the function is only executed once the user has paused.