JAVASCRIPT
Custom React Hook for Debouncing Values
Optimize performance by delaying state updates with a custom React useDebounce hook, preventing excessive re-renders and API calls during rapid input.
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;
}
How it works: The useDebounce hook delays updating a value until a specified `delay` has passed without any new updates. It uses `useState` to hold the debounced value and `useEffect` to set up and clear a `setTimeout`. This is crucial for performance optimization in search bars or input fields to reduce frequent re-renders or API calls to a backend.