JAVASCRIPT
useDebounce Hook for Delaying State Updates
Implement a custom `useDebounce` React hook to delay the update of a value, preventing excessive re-renders or API calls during rapid input changes.
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
// Example Usage:
// import React, { useState, useEffect } from 'react';
// function SearchInput() {
// 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: This `useDebounce` hook takes a value and a delay. It returns a debounced version of that value. The `useEffect` hook sets a timeout to update the `debouncedValue` state. If the original `value` changes before the timeout completes, the previous timeout is cleared, and a new one is set. This ensures the `debouncedValue` only updates after the specified `delay` has passed without further changes to the input `value`, which is useful for optimizing expensive operations like API calls or filtering during user input.