JAVASCRIPT

Implement a Custom `useDebounce` Hook in React

Learn how to create a reusable `useDebounce` React hook to delay state updates, optimizing performance for search inputs and other frequently changing values.

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 MyComponent() {
//   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 delays updating a value until a specified time `delay` has passed since its last change. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` to set the new value. The `clearTimeout` in the effect's cleanup function ensures that if the original value changes before the delay, the previous timer is cleared, preventing unnecessary updates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs