JAVASCRIPT

Custom useDebounce Hook for Input Delay

Learn to create a `useDebounce` custom React hook to delay state updates, optimizing performance for search inputs or frequently triggered 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

//   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 custom `useDebounce` hook delays updating a value until a specified `delay` time has passed without further changes to the input `value`. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` and `clearTimeout` to manage the delay. This is extremely useful for optimizing performance in scenarios like search bars, where you want to avoid making API calls on every keystroke.

Need help integrating this into your project?

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

Hire DigitalCodeLabs