JAVASCRIPT

`useDebounce` Custom Hook for Input Throttling

Learn to create a `useDebounce` custom React hook to delay state updates, perfect for optimizing search inputs or preventing excessive 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); // 500ms delay

  useEffect(() => {
    if (debouncedSearchTerm) {
      console.log('Fetching data for:', debouncedSearchTerm);
      // Perform API call or heavy computation here
    }
  }, [debouncedSearchTerm]);

  return (
    <input
      type="text"
      placeholder="Search..."
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
    />
  );
}
*/
How it works: The `useDebounce` hook delays updating a `debouncedValue` state until a specified `delay` has passed without the `value` changing. It uses `useEffect` to set a timeout whenever `value` or `delay` changes. If the `value` changes again before the timeout completes, the previous timeout is cleared, and a new one is set, effectively resetting the timer. This prevents rapid updates, which is ideal for search bars or auto-save features.

Need help integrating this into your project?

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

Hire DigitalCodeLabs