JAVASCRIPT

Debounce Any Value with `useDebounce` React Hook

Implement a generic `useDebounce` hook in React to delay updates of any value until a specified time has passed, optimizing performance for search inputs, resizing, and more.

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);
//
//   // Effect for API call or expensive operation
//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Searching 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 takes a `value` and a `delay`. It maintains a `debouncedValue` state. A `useEffect` sets a timeout to update `debouncedValue` with the latest `value` after the specified `delay`. If the `value` changes again before the timeout completes, the previous timeout is cleared, and a new one is set, effectively delaying the update until the `value` stops changing for the duration of the `delay`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs