← Back to all snippets
JAVASCRIPT

Debouncing Any Value in React with a Custom useDebounce Hook

Implement a versatile `useDebounce` hook in React to delay updates of any value, optimizing performance by reducing frequent computations or 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 SearchInput() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500);
//
//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Fetching data for:', debouncedSearchTerm);
//       // Perform API call or heavy computation 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 state variable until a specified `delay` period has passed without the `value` changing. It uses `useState` for the debounced value and `useEffect` with `setTimeout` to manage the delay. Each time the `value` changes, the previous timer is cleared and a new one is set, ensuring the `debouncedValue` only updates after the input has settled. This is crucial for optimizing performance in scenarios like search bars or expensive computations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs