JAVASCRIPT
Implement a Custom useDebounce Hook for React
Learn to create a reusable React useDebounce hook to delay state updates, optimizing performance for inputs like search bars and preventing excessive re-renders.
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;
}
// How to use it:
// function SearchInput() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay
// useEffect(() => {
// if (debouncedSearchTerm) {
// // Perform API call or heavy computation here
// console.log('Searching for:', debouncedSearchTerm);
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: The `useDebounce` hook takes a `value` and a `delay`. It maintains an internal `debouncedValue` state. Whenever the `value` changes, a `setTimeout` is set. If `value` changes again before the delay, the previous timeout is cleared and a new one is set. This ensures `debouncedValue` only updates after the specified `delay` has passed without any new changes to the `value`, making it perfect for optimizing frequent updates like search inputs.