JAVASCRIPT

Implement a Custom `useDebounce` Hook

Create a custom React hook to debounce any value, useful for optimizing performance of frequently changing inputs like search bars or heavy computations.

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;
}

// How to use it:
// function SearchInput() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay

//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Fetching data for:', debouncedSearchTerm);
//       // Perform API call or other expensive operation
//     }
//   }, [debouncedSearchTerm]);

//   return (
//     <input
//       type="text"
//       placeholder="Search..."
//       value={searchTerm}
//       onChange={(e) => setSearchTerm(e.target.value)}
//     />
//   );
// }
How it works: This custom hook delays updating a value until a specified time has passed since its last change. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` and `clearTimeout` to manage the delay, ensuring that the effect only runs after the value has stabilized. This is particularly useful for optimizing performance for inputs that trigger expensive operations, like searching or filtering data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs