JAVASCRIPT
Implement a useDebounce Hook for Input Values
Learn how to create a custom React useDebounce hook to delay state updates, perfect for optimizing search inputs or filtering data to reduce API calls and improve 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;
}
How it works: This `useDebounce` hook delays updating a value until a specified `delay` has passed without any new updates to the original `value`. It's ideal for optimizing performance in search bars, text inputs, or filters, preventing excessive re-renders or API calls by only reacting once the user has paused typing, leading to a smoother user experience.