JAVASCRIPT

Implement a Debounce Hook for React Inputs

Learn how to create a custom `useDebounce` React hook to delay executing a function until after a certain time, optimizing performance for search inputs or expensive operations.

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

//   return (
//     <input
//       type="text"
//       placeholder="Search..."
//       value={searchTerm}
//       onChange={(e) => setSearchTerm(e.target.value)}
//     />
//   );
// }
How it works: This `useDebounce` hook allows you to debounce any value. It returns a debounced version of the input `value` that will only update after the specified `delay`. This is particularly useful for optimizing performance in scenarios like search bars, where you don't want to trigger an API request on every keystroke, but rather after the user has paused typing for a short duration.

Need help integrating this into your project?

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

Hire DigitalCodeLabs