JAVASCRIPT
Debounce State Updates with a Custom Hook
Learn to create a custom React hook for debouncing any state value, optimizing performance by delaying updates until user input settles, preventing excessive re-renders.
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Set debouncedValue to value (latest value) 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
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) {
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 custom `useDebounce` hook takes a value and a delay. It returns a new 'debounced' value that only updates after the specified `delay` has passed since the last change to the original `value`. It's ideal for optimizing expensive operations like API calls or heavy computations that depend on rapidly changing inputs, ensuring they don't fire too frequently.