← Back to all snippets
JAVASCRIPT

Debouncing Input Values and Functions with `useDebounce`

Implement a custom `useDebounce` React hook to delay state updates or function calls, optimizing performance for search inputs or frequent events.

import { useState, useEffect } from 'react';

function useDebounce(value, delay) {
  // State to store debounced value
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    // Set a timeout to update debounced value after the specified delay
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    // Cleanup function: Clear timeout if value changes before the delay
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]); // Only re-run if value or delay changes

  return debouncedValue;
}

// Example Usage:
/*
function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms debounce

  // Effect for API call whenever debouncedSearchTerm changes
  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Fetching data for:', debouncedSearchTerm);
      // performApiSearch(debouncedSearchTerm);
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: The `useDebounce` hook takes a `value` and a `delay` and returns a debounced version of that value. It uses `useState` to hold the debounced value and `useEffect` to manage a timeout. When the input `value` changes, a new timeout is set. If the `value` changes again before the `delay` has passed, the previous timeout is cleared (via the `useEffect` cleanup function) and a new one is set. This ensures that the `debouncedValue` is only updated after a period of inactivity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs