← Back to all snippets
JAVASCRIPT

Create a Custom useDebounce Hook for Input Fields

Develop a reusable custom React `useDebounce` hook to delay execution of a function until after a certain time has passed without further calls, perfect for search inputs.

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);
    } else {
      console.log('No search term yet or cleared.');
    }
  }, [debouncedSearchTerm]);

  return (
    <div>
      <input
        type="text"
        placeholder="Type to search..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p>Original input: {searchTerm}</p>
      <p>Debounced search: {debouncedSearchTerm}</p>
      <p>The "Searching for" console log will only appear 500ms after you stop typing.</p>
    </div>
  );
}

export default SearchInput;
How it works: The `useDebounce` custom hook takes a `value` and a `delay` as input. It returns a `debouncedValue` which only updates after the `delay` has passed since the last change to the input `value`. This is achieved using `useEffect` to set a `setTimeout` and `clearTimeout`. This hook is highly useful for scenarios like search inputs, where you want to perform an action (e.g., an API call) only after the user has stopped typing for a certain period, reducing unnecessary requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs