← Back to all snippets
JAVASCRIPT

Custom useDebounce Hook for Input Fields

Create a reusable custom React hook, `useDebounce`, to delay expensive operations like API calls until the user stops typing, improving performance.

import React, { 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;
}

function SearchInput() {
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Searching for:', debouncedSearchTerm); // Simulate API call
    } else {
      console.log('Search term cleared');
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Type to search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}

export default SearchInput;
How it works: This custom `useDebounce` hook provides a practical solution for delaying updates or side effects, commonly used in search inputs to prevent making an API request on every keystroke. It utilizes `useState` to hold the debounced value and `useEffect` with a cleanup function to manage a timer. The effect runs whenever the `value` or `delay` changes, resetting the timer. The `debouncedValue` is only updated after the specified `delay`, ensuring that expensive operations are only performed when the user has paused typing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs