JAVASCRIPT
Efficiently Debounce User Input with `useDebounce` Hook
Learn how to create a custom React `useDebounce` hook to delay state updates, perfect for optimizing search inputs, auto-save features, 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;
}
// Example Usage:
// function SearchInput() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500);
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Searching 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: The `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 and clear a timeout. Each time the `value` or `delay` changes, the previous timeout is cleared, and a new one is set. This is incredibly useful for search bars, auto-save functionalities, or any scenario where you want to limit the frequency of an expensive operation triggered by frequent user input.