JAVASCRIPT

Implement a useDebounce Hook for Input Optimization

Create a custom React hook to debounce any value, useful for delaying state updates from fast-changing inputs like search fields and improving performance.

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) {
//       // Perform API call or heavy computation with debouncedSearchTerm
//       console.log('Fetching data for:', debouncedSearchTerm);
//     }
//   }, [debouncedSearchTerm]);

//   return (
//     <input
//       type="text"
//       placeholder="Search..."
//       value={searchTerm}
//       onChange={(e) => setSearchTerm(e.target.value)}
//     />
//   );
// }
How it works: This `useDebounce` hook takes a value and a delay, returning a new value that only updates after the specified delay has passed without the original value changing. It's perfect for scenarios like search inputs where you want to wait for the user to finish typing before triggering an expensive operation, thus optimizing performance and reducing unnecessary re-renders or API calls.

Need help integrating this into your project?

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

Hire DigitalCodeLabs