DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Debouncing in React: Preventing Unnecessary Re-Renders and API Calls

When working with search bars or live filtering in React, one common challenge is avoiding unnecessary API calls while the user is still typing. For example, if a user types "apple," you don’t want to send five API requests for each keystroke (a, ap, app, appl, apple). Instead, you want to wait until the user pauses typing and then trigger the search.

This is where debouncing comes into play. Debouncing ensures that a function only executes after a specified period of inactivity. In React, we can achieve this behavior using a custom hook.


The Custom useDebounce Hook

Let’s look at the code:

import React, { useEffect, useState } from "react";

const useDebounce = (inputValue, timeOut) => {
  const [text, setText] = useState(undefined);

  useEffect(() => {
    const debounceTimeout = setTimeout(() => {
      setText(inputValue);
    }, timeOut);

    return () => {
      clearTimeout(debounceTimeout);
    };
  }, [inputValue, timeOut]);

  return { text };
};
Enter fullscreen mode Exit fullscreen mode

🔍 How it works:

  1. State (text) → Stores the debounced value.
  2. Effect → Every time inputValue or timeOut changes, a new timeout is set.
  3. Cleanup → If the user types again before the timeout finishes, the previous timeout is cleared.
  4. Final Behavior → Only after the user stops typing for the specified delay (timeOut), the value gets updated.

Using the Hook in a Search Bar

Here’s how we can integrate useDebounce inside a search bar component:

const SearchBar = () => {
  const [inputValue, setInputValue] = useState("");
  const { text } = useDebounce(inputValue, 500); // 500ms debounce delay

  console.log(text); // This updates only after user stops typing for 500ms

  return (
    <input
      type='text'
      value={inputValue}
      onChange={(e) => setInputValue(e.target.value)}
      placeholder='Search...'
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

Example Flow:

  • User types hello.
  • Keystrokes happen rapidly → debounce cancels previous timeouts.
  • After 500ms pause, the hook sets text = "hello".
  • This debounced value can now be used to call an API or filter a list.

Why Use useDebounce?

✅ Prevents excessive API calls.
✅ Improves performance in search-heavy applications.
✅ Enhances user experience by reducing flickering results.
✅ Can be reused across multiple components.


Real-World Applications

  • Search bars (Google-like instant search).
  • Form validation with delay.
  • Autosave functionality.
  • Filtering large data sets.

Final Thoughts

The useDebounce hook is a must-have utility in React applications where user input triggers expensive operations like API calls. By introducing a slight delay, we make apps more efficient and user-friendly.


Top comments (0)