← Back to all snippets
JAVASCRIPT

Debouncing Input with a Custom useDebounce Hook

Implement a `useDebounce` custom hook in React to delay state updates from rapid user input, optimizing performance for search bars or other frequent interactions.

import React, { useState, useEffect } from 'react';

// Custom hook for debouncing a value
function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

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

    // Cleanup function: Clear the timeout if value changes or component unmounts
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]); // Rerun effect if value or delay changes

  return debouncedValue;
}

// Component using the useDebounce hook
function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500); // Debounce by 500ms

  // This effect will only run after the debounced search term changes
  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Searching for:', debouncedSearchTerm);
      // In a real app, you would fetch data here
    }
  }, [debouncedSearchTerm]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p>Current search term: {searchTerm}</p>
      <p>Debounced search term (for API): {debouncedSearchTerm}</p>
    </div>
  );
}

export default SearchInput;
How it works: The `useDebounce` custom hook takes a `value` and a `delay`. It maintains a `debouncedValue` state. Whenever the `value` changes, `useEffect` sets a timeout to update `debouncedValue` after the `delay`. If the `value` changes again before the timeout expires, the previous timeout is cleared, and a new one is set. This ensures that the `debouncedValue` only updates after a pause in changes, which is ideal for optimizing expensive operations like API calls triggered by rapid user input in a search bar.

Need help integrating this into your project?

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

Hire DigitalCodeLabs