JAVASCRIPT
Create a Custom `useDebounce` Hook for Input Optimization
Learn to build a reusable `useDebounce` custom hook to delay executing a function until after a certain period of inactivity. Perfect for optimizing search inputs or API calls.
import { useState, useEffect } from 'react';
export function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Set debouncedValue to value after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Return a cleanup function that will be called on unmount or if value/delay changes
return () => {
clearTimeout(handler);
};
}, [value, delay]); // Only re-call effect if value or delay changes
return debouncedValue;
}
// Example Usage in a component:
// function SearchInput() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500);
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Fetching data for:', debouncedSearchTerm); // Simulate API call
// // fetchData(debouncedSearchTerm);
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This custom `useDebounce` hook provides a debounced version of any value. It uses `useState` to store the debounced value and `useEffect` to manage a timeout. When the `value` changes, the `useEffect` clears any previous timeout and sets a new one. The `debouncedValue` is only updated after the `delay` has passed without further changes to the `value`, making it ideal for optimizing frequent updates like search inputs to reduce API calls.