JAVASCRIPT
useDebounce Hook for Input Value Throttling
Learn to create a custom React `useDebounce` hook to delay state updates, perfect for search inputs or any value that needs a pause before triggering actions, optimizing performance.
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); // 500ms delay
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Performing search for:', debouncedSearchTerm);
// // Perform action with debouncedSearchTerm, e.g., filter a list or fetch data
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type='text'
// placeholder='Search...'
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This `useDebounce` hook delays updating a value until a specified `delay` time has passed without further changes to the input `value`. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` to manage the delay. Each time the `value` changes, the previous timeout is cleared, and a new one is set. This is highly useful for optimizing performance in search bars, autosave features, or any scenario where frequent updates based on user input are expensive.