JAVASCRIPT
Creating a `useDebounce` Hook for Delayed Value Updates
Learn to create a custom `useDebounce` React hook to delay updates of any value, perfect for optimizing search inputs, filtering, and API calls by reducing unnecessary re-renders or 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 SearchInput() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounce(searchTerm, 500);
useEffect(() => {
if (debouncedSearchTerm) {
console.log('Fetching data for:', debouncedSearchTerm);
// Perform API call here
}
}, [debouncedSearchTerm]);
return (
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
*/
How it works: This custom `useDebounce` hook delays updating a value until a specified `delay` time has passed without the value changing. It uses `useState` to hold the debounced value and `useEffect` to set a timeout. Each time the `value` or `delay` changes, the previous timeout is cleared and a new one is set, ensuring that the `setDebouncedValue` only runs after the specified inactivity period. This is crucial for optimizing performance in scenarios like search inputs where you don't want to trigger an event on every keystroke.