← Back to all snippets
JAVASCRIPT

Debounce User Input with useDebounce Hook

Implement a custom React `useDebounce` hook to delay execution of functions, perfect for optimizing search inputs, window resizing, or other frequent 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 SearchInput() {
//   const [searchTerm, setSearchTerm] = useState('');
//   const debouncedSearchTerm = useDebounce(searchTerm, 500);

//   useEffect(() => {
//     if (debouncedSearchTerm) {
//       console.log('Searching 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: The `useDebounce` hook delays updating a value until a specified `delay` has passed without any further changes. This is crucial for performance optimization, preventing excessive re-renders or API calls when dealing with rapidly changing inputs like search boxes, where you only want to act once the user has stopped typing. It uses `setTimeout` to defer the state update and `clearTimeout` in its cleanup function to reset the timer if the value changes again before the delay expires.

Need help integrating this into your project?

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

Hire DigitalCodeLabs