← Back to all snippets
JAVASCRIPT

Debounce a Value with the useDebounce Hook

Learn to create a useDebounce React hook to delay state updates, perfect for optimizing search inputs and preventing excessive re-renders or API calls.

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('Fetching data for:', debouncedSearchTerm);
      // Perform API call or search logic here
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: This useDebounce hook takes a `value` and a `delay` as input. It maintains an internal `debouncedValue` state. Whenever the `value` changes, a `setTimeout` is set. If the `value` changes again before the `delay` expires, the previous `setTimeout` is cleared and a new one is set. This ensures the `debouncedValue` is only updated after the specified `delay` has passed without any new changes to the original `value`, effectively "debouncing" updates.

Need help integrating this into your project?

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

Hire DigitalCodeLabs