Introducing the useDebounce Hook

Apr 24, 2024

Introducing the useDebounce Hook

Learn how to optimize your React applications with the useDebounce hook. This powerful tool simplifies debouncing, enhancing performance and user experience.

Author

Daya
DayaSoftware Engineer III

Subject Matter Expert

Tarun Bhagchand Soni
Tarun Bhagchand SoniSenior Software Engineer - II
useDebounce - StackBlitz
Click On The Image Above To Watch How It Works

The useDebounce hook is a functional component that provides a reusable way to implement debouncing in your React applications. It takes two arguments:

  • value: This is the value you want to debounce, typically a state variable holding user input (e.g., search term). It can be any data type (T).
  • delay (optional): This is the delay in milliseconds after which the debounced value will be updated. It defaults to 500ms (half a second).


Under the Hood: How the Hook Works

  1. State Management: The hook utilizes the useState hook to create two state variables:
    • debouncedValue: This stores the currently debounced value. It's initialized with the initial value passed to the hook.
    • (Optional, but recommended) timeoutId: This can store the ID of the currently running timeout for better cleanup.
  2. useEffect for Debouncing Magic: The useEffect hook is responsible for the debouncing logic and runs whenever the value or delay dependencies change:
    • Timeout Creation: Inside the useEffect, a timeout is created using setTimeout. This timeout is set to trigger after the specified delay milliseconds.
    • Debounced Value Update: When the timeout fires, the setDebouncedValue function is called. This function updates the debouncedValue state with the current value.
    • Cleanup Function: A cleanup function is returned by the useEffect. This function is crucial for preventing memory leaks. It uses clearTimeout to clear any pending timeout when the component unmounts or the dependencies change.
  3. Returning the Debounced Value: Finally, the hook returns the current debouncedValue. This value will only be updated after the specified delay has passed since the last change in the original value.


Benefits of Using useDebounce

  • Improved Performance: By using the debounced value for actions like API calls or UI updates, you avoid unnecessary requests and computations, leading to a smoother user experience.
  • Optimized Server Interactions: Debouncing helps prevent overloading servers with rapid requests, improving both user and server performance.
  • Enhanced User Experience: By delaying actions until user input settles, you reduce flickering or premature updates, making the UI feel more responsive and intuitive.
  • Code Reusability: The useDebounce hook is a reusable component, promoting better code organization and maintainability across your React projects.


Putting It into Practice: Integrating useDebounce

Let's see how you can utilize the useDebounce hook in your React component:

import { useEffect, useState } from 'react';

function useDebounce<T>(value: T, delay: number = 500): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return debouncedValue;
}

export default useDebounce;
import { useEffect, useState } from 'react';
import './App.css';
import useDebounce from './hooks/useDebounce';

type Character = {
  id: number;
  name: string;
  image: string;
};

function App() {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [data, setData] = useState<Character[] | undefined>([]);
  const [apiCount, setApiCount] = useState<number>(0);

  const debouncedSearchTerm = useDebounce(searchTerm, 1000);

  useEffect(() => {
    fetch(
      `https://rickandmortyapi.com/api/character/?name=${debouncedSearchTerm}`
    )
      .then((res) => res.json())
      .then((data: { results: Character[] }) => {
        setData(data.results);
        setApiCount(apiCount + 1);
      })
      .catch((error) => console.error('Error fetching characters:', error));
  }, [debouncedSearchTerm]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(event.target.value);
  };

  return (
    <div className="container">
      <input
        type="text"
        placeholder="Search character..."
        value={searchTerm}
        onChange={handleChange}
      />
      <div className="api-count">API hit: {apiCount} times</div>
      <div className="character-list">
        {data === undefined && 'Nothing Found.'}
        {data &&
          data.map((character) => (
            <div key={character.id} className="character">
              <img src={character.image} alt={character.name} />
              <div>{character.name}</div>
            </div>
          ))}
      </div>
    </div>
  );
}

export default App;
Hire us form


Conclusion

In conclusion, the useDebounce hook is a valuable tool for React developers. It provides a clean and reusable way to implement debouncing, improving the performance and user experience of your applications. By delaying actions until user input settles, you can optimize server interactions, reduce unnecessary computations, and create a more responsive and intuitive UI. Consider incorporating the useDebounce hook into your React projects to enhance their overall quality and efficiency.

Subscribe to Our Newsletter

More from the engineering frontline.

Dive deep into our research and insights on design, development, and the impact of various trends to businesses.
Insight
Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages
Sep 11, 2026

Building Local LLMs Using Dart FFI And llama.cpp: Beyond Wrapper Packages

Build local LLMs in Flutter with Dart FFI and llama.cpp, and see how native bridges, GGUF models, memory management, and token streaming enable private, on-device AI.

Insight
My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong
Sep 11, 2026

My Flutter App Froze With Three Photos on Screen. Here's What I Was Doing Wrong

This blog explains how rethinking Flutter’s image-processing architecture fixed severe performance issues and improved rendering efficiency.

Insight
Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15
Sep 10, 2026

Building a Production-Ready Canva-like Editor with Konva.js, React 19 and Next.js 15

This blog explains how to build a production-ready canvas editor with Konva.js, React, and Next.js, covering architecture, performance, and key engineering decisions.

Insight
What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust
Sep 8, 2026

What a PHP-to-NestJS Banking Migration Taught Us About Architecture, Security, and Trust

This blog explores the architecture, security, performance, and documentation lessons from migrating a legacy PHP/Laravel banking platform to NestJS.

Insight
Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs
Sep 7, 2026

Building Production-Grade Video Thumbnail Scrubbing in the Browser: HLS, Frame Extraction, Caching, and Performance Trade-offs

This blog explains how to build responsive video thumbnail scrubbing in the browser for local files and HLS streams, covering frame extraction, caching, and performance trade-offs.

Insight
The Agent Can See Your App. How Often Can It Look?
Sep 4, 2026

The Agent Can See Your App. How Often Can It Look?

AI coding agents can now interact with mobile apps, but their effectiveness depends on iteration speed. This blog explores how React Native architecture influences feedback loops and AI-driven developer productivity.

Insight
Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists
Sep 1, 2026

Building Interactive Cards from Design JSON Without Killing Your Feed: Overlays, Video, Mute/Unmute, and Lag-Free Lists

Learn how to turn design JSON into interactive, video-enabled cards using overlays, smart media controls, caching, and virtualization without slowing down high-cardinality feeds.

The Right Conversation Can

Save You Six Months.

Book a call
Introducing the useDebounce Hook - GeekyAnts