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

useDebounce Example

Create a hook that returns a debounced version of a value using useState and useEffect with setTimeout.

What You'll Learn

You'll learn how to create a useDebounce custom hook that delays updating a value until the user stops changing it for a specified time—perfect for search inputs and other rapid-fire updates.

The Problem: Too Many Updates

Imagine typing in a search box that triggers an API call on every keystroke. Type "react" and you've fired 5 requests! Debouncing waits until you stop typing before acting, like a patient librarian who waits for you to finish asking your question.

Building useDebounce

This custom hook takes a value and a delay, then returns a debounced version that only updates after the delay period passes without changes:

import { useState, useEffect } from 'react';

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

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

    // Clean up: cancel timer if value changes again
    return () => {
      clearTimeout(timeoutId);
    };
  }, [value, delay]);

  return debouncedValue;
}

Using It in Practice

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

  useEffect(() => {
    if (debouncedSearchTerm) {
      // Only fires 500ms after user stops typing
      console.log('Searching for:', debouncedSearchTerm);
      // Make your API call here
    }
  }, [debouncedSearchTerm]);

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

Every keystroke resets the timer via cleanup, so the debounced value only updates when typing pauses.

Key Takeaway: useDebounce combines useState and useEffect with setTimeout cleanup to create a delayed version of a rapidly-changing value, reducing unnecessary operations like API calls.