JAVASCRIPT
Efficient Input Handling with useDebounce Hook
Optimize React component performance by debouncing state updates for user inputs like search fields, preventing excessive re-renders and API calls.
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 SearchBar() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500);
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Fetching data for:', debouncedSearchTerm);
// // Perform API call 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` has passed without any further changes. This is crucial for optimizing performance in applications, especially for features like search bars, where API calls or heavy computations should only occur after the user stops typing. The `useEffect` cleanup function ensures previous timeouts are cleared, preventing stale updates.