JAVASCRIPT
Debounce Any Value with a Custom React Hook
Implement a custom React hook to debounce any value, useful for optimizing performance in search inputs, resizing, or frequently triggered events.
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
// State to store debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Set a timeout to update debounced value after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cleanup function: Clear timeout if value changes (or component unmounts)
// This ensures that the debounced value is only updated after the delay
// has passed without any new changes to the original value.
return () => {
clearTimeout(handler);
};
}, [value, delay]); // Only re-call effect if value or delay changes
return debouncedValue;
}
export default useDebounce;
// Example Usage:
// function SearchInput() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500); // Debounce by 500ms
//
// 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 provides a debounced version of any given value. It takes a value and a delay, returning the value only after the specified delay has passed without any further updates to the original value. This is highly useful for optimizing performance by limiting the frequency of expensive operations, such as API calls triggered by user input or resizing events.