Course contentsShow
← React
Lesson 991 of 2,39625. Custom HooksFree lesson

useDebounce: Composing useState with useEffect Cleanup

Create a debounce hook that combines state, effects, and cleanup to delay value updates for search inputs.

useDebounce: Composing useState with useEffect Cleanup

What you'll learn: How to build a custom useDebounce hook that delays updating a value until the user stops typing, combining state management with effect cleanup.

The Core Idea

Debouncing is like waiting for someone to finish talking before you respond. When a user types in a search box, you don't want to fire off API requests after every single keystroke—that's wasteful. Instead, you wait until they've stopped typing for a moment (say, 500ms) before acting on the final value.

This hook combines useState to track the delayed value and useEffect with cleanup to reset the timer whenever the input changes.

How It Works

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

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

    // Cleanup: cancel the timer if value changes again
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

Every time value changes, the effect runs. It starts a timer, but if value changes again before the timer completes, the cleanup function cancels that timer and starts fresh. Only when the user pauses does the timer complete and update debouncedValue.

Using It

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

  // This effect only runs when typing stops for 500ms
  useEffect(() => {
    if (debouncedSearchTerm) {
      // Make API call with debouncedSearchTerm
    }
  }, [debouncedSearchTerm]);

  return <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} />;
}

Key Takeaway: useDebounce combines useState and useEffect cleanup to create a delayed value that only updates after rapid changes stop, perfect for optimizing search inputs and API calls.