JAVASCRIPT
Custom Hook for Debounced Input Value
Learn to create a reusable React hook that debounces an input value, preventing excessive function calls during user typing and improving performance in search fields or forms.
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 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, returning a new value that only updates after the specified delay has passed since the last change to the original value. It's incredibly useful for optimizing performance in search inputs, auto-save features, or any scenario where you want to defer an action until a user has stopped typing or interacting for a short period, thereby reducing the number of expensive operations like API calls.