JAVASCRIPT
How to implement a useDebounce hook for input fields
Create a custom React useDebounce hook to delay state updates, optimizing performance for fast-typing search inputs or frequent event handlers.
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 data fetching 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 time has passed without further changes. It uses setTimeout to schedule the update and clearTimeout to cancel any previous pending updates, effectively preventing rapid re-renders or API calls when a value changes frequently.