DEV Community

Cover image for Debouncing Made Simple: Improve React Performance with Delayed Execution
Jaligama Satyaveer
Jaligama Satyaveer

Posted on

1

Debouncing Made Simple: Improve React Performance with Delayed Execution

Debouncing is a programming technique used to limit the rate at which a function executes. It is particularly useful when dealing with events that fire frequently, such as keystrokes, API calls etc.

Why Debouncing?

For example, when users type in a search box, the input event is triggered every time a key is pressed. Without debouncing, an API call would be made on every keystroke, causing unnecessary network requests. Debouncing ensures that the function (e.g., API call) executes only after the user has stopped typing for a certain period.

Implementing Debouncing

1. Setting up state

const [fieldValue, setFieldValue] = useState("");
Enter fullscreen mode Exit fullscreen mode

2. API Call Function

const getData = () => {
  console.log("----API Call----");
};
Enter fullscreen mode Exit fullscreen mode

This function simulates an API call by logging "----API Call----" to the console.

3. Implementing Debouncing using useEffect

useEffect(() => {
  const apiCallTimeout = setTimeout(() => {
    getData();
  }, 2000);

  return () => clearTimeout(apiCallTimeout);
}, [fieldValue]);
Enter fullscreen mode Exit fullscreen mode
  • Whenever fieldValue changes, the effect runs.
  • A setTimeout is set for 2000 milliseconds (2 seconds) to call getData().
  • If the user continues typing before the 2-second delay, the previous setTimeout is cleared, and a new one starts.
  • The cleanup function (return () => clearTimeout(apiCallTimeout);) ensures that only the last keystroke (after the user stops typing) triggers the API call.

4. Without Debouncing

// useEffect(() => {
//   getData();
// }, [fieldValue]);
Enter fullscreen mode Exit fullscreen mode
  • If this version is used, getData() would run every time fieldValue changes, causing multiple API calls for every keystroke.
  • This leads to unnecessary network requests and potential performance issues.

5. Input Field

return (
  <div className="App">
    <input
      type="text"
      onChange={(e) => setFieldValue(e.target.value)}
      value={fieldValue}
      placeholder="Search"
    />
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Full Code

import { useEffect, useState } from "react";

function DebouncingExample() {
  const [fieldValue, setFieldValue] = useState("");

  const getData = () => {
    console.log("----API Call----");
  };

  // ------------------Debouncing--------------------
  useEffect(() => {
    const apiCallTimeout = setTimeout(() => {
      getData();
    }, 2000);

    return () => clearTimeout(apiCallTimeout);
  }, [fieldValue]);

  // ----------------Without debouncing------------------
  // useEffect(() => {
  //   getData();
  // }, [fieldValue]);

  return (
    <div className="App">
      <input
        type="text"
        onChange={(e) => setFieldValue(e.target.value)}
        value={fieldValue}
        placeholder="Search"
      />
    </div>
  );
}

export default DebouncingExample;
Enter fullscreen mode Exit fullscreen mode
  • Debouncing is an essential technique to improve performance and avoid excessive function executions. In this case, it helps prevent multiple API calls on every keystroke by delaying execution until the user pauses typing.

  • It is widely used in search boxes, form validations, and resize events to improve efficiency and user experience.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️