JAVASCRIPT
Custom `useDebounce` Hook for Input Throttling
Learn to create a custom React `useDebounce` hook to delay execution of functions, perfect for search inputs, preventing excessive API calls, and improving performance.
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Set a timeout to update debounced value after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cleanup function: Cancel the timeout if value changes or component unmounts
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);
// useEffect(() => {
// if (debouncedSearchTerm) {
// // Perform API call or expensive operation here
// console.log('Performing search for:', debouncedSearchTerm);
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This `useDebounce` hook takes a `value` and a `delay` as arguments. It maintains an internal `debouncedValue` state. Whenever the `value` changes, a new `setTimeout` is set to update `debouncedValue` after the specified `delay`. If the `value` changes again before the delay expires, the previous timeout is cleared, and a new one is set. This ensures the action (e.g., API call) only fires after the user stops typing for the given `delay`, significantly improving performance and reducing server load for search inputs or other frequent event handlers.