JAVASCRIPT

Create a useDebounce Custom Hook for React Inputs

Learn how to implement a useDebounce custom hook in React to delay state updates, optimizing performance for search inputs and frequent user interactions.

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: This `useDebounce` hook postpones updating a value until a specified `delay` has passed since the last change. It uses `useState` to store the debounced value and `useEffect` with a `setTimeout` to manage the delay. Each time the `value` changes, the previous timeout is cleared, and a new one is set. This is highly useful for optimizing performance in search bars, autosave features, or any scenario where frequent input triggers expensive operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs