JAVASCRIPT

Implement a useDebounce Hook for Delayed Value Updates

Learn how to create a custom React useDebounce hook to delay updating a value until a specified time has passed, perfect for search inputs or frequent events.

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 SearchBar() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay

//   // Effect for API call or action after debounce
//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Performing search for:', debouncedSearchTerm);
//       // fetchData(debouncedSearchTerm);
//     }
//   }, [debouncedSearchTerm]);

//   return (
//     <input
//       type="text"
//       placeholder="Search..."
//       value={searchTerm}
//       onChange={(e) => setSearchTerm(e.target.value)}
//     />
//   );
// }
How it works: This custom `useDebounce` hook delays updating a value for a specified `delay` period. It uses `useState` to hold the debounced value and `useEffect` to set a timeout. If the original `value` changes before the timeout clears, the previous timeout is cleared, and a new one is set, effectively resetting the debounce timer. This is highly useful for optimizing performance in search bars, text inputs, or any event that fires frequently, preventing unnecessary re-renders or API calls.

Need help integrating this into your project?

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

Hire DigitalCodeLabs