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

S

Safal Bhandari

Guest
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:


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 };
};

πŸ” 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:


Code:
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...'
    />
  );
};

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.

Continue reading...
 


Join 𝕋𝕄𝕋 on Telegram
Channel PREVIEW:
Back
Top