Front-end Optimization: Debouncing

ishjotsb

Ishjot Singh

Posted on September 28, 2024

Front-end Optimization: Debouncing

Introduction

When building React applications, performance is a key concern—especially when dealing with events that fire rapidly, such as typing in a search box, resizing the window, or scrolling through a page. Without proper control, these frequent event triggers can lead to unnecessary renders, API calls, or state updates, slowing down your application.

Recently, I was working on a project where I had to implement a search tab with an autocomplete feature. So I wrote the code for this where my backend was sent a request by my React application whenever the user typed something in the search box. The API was called for every key pressed. I paused and thought to myself, "Wait this doesn't make any sense?" "An API call for every keystroke?" "What if someone just smashes keys on their keyboard?" 100s of API calls within seconds. That's expensive.

This is where debouncing comes in. Debouncing helps by delaying the execution of a function until a certain amount of time has passed since it was last invoked. In React, this can prevent excessive re-renders or API requests, ultimately improving the performance and user experience of your app.

What exactly is Debouncing?

In simple terms, debouncing is a programming technique used to limit how often a function called. When dealing with frequently occurring events, such as typing in a search box, it is important to ensure that the function is not called every time the event is triggered, and instead given a pause in the activity.

Think of debouncing as a way to wait for the user to "finish" an action before responding to it. For example, if a user is typing into a search bar, you don’t want to send a request after every keystroke. Instead, you wait until they stop typing for a certain period (say 300 milliseconds) before making the API call.

Why Debouncing is so useful?

In React, components often need to respond to user input or other events. However, uncontrolled re-renders or frequent updates can degrade performance. Debouncing helps to:

  • Reduce Unnecessary Re-renders: React re-renders components whenever state changes. Debouncing ensures that the state is only updated after a delay, thus preventing excessive renders.

  • Optimize API Requests: In cases like search bars or filters, debouncing can ensure that API requests are made only when the user has stopped typing, reducing server load.

  • Smooth UI: Continuous triggering of expensive computations like filtering, sorting, or animations can make the UI sluggish. Debouncing smooths out these operations, improving user experience.

How Debouncing works in React

At its core, debouncing works by wrapping your function call with a setTimeout function to delay its calling.
Here's a code snippet of debouncing in action:

useEffect(() => {
    if (data) {
      setFormData(initialFormData);
      toast.success(data.message);
    } 

    // API Call made using the searchMarket method
    const timer = setTimeout(searchMarket, 300);

    return () => {
      clearTimeout(timer);
    }
  }, [data, formData.name]);
Enter fullscreen mode Exit fullscreen mode

Image description

Let's breakdown this code to implement an autocomplete functionality in the search box:

  • useEffect hook is called first to ensure the API call is made after all the components have rendered.
  • searchMarket is the method which contains the API call made to retrieve the results as per the user input.
  • The method searchMarket is called every 300ms using the setTimeout method which is an inbuilt JavaScript method to delay the function call.

This ensures that the searchMarket method is only called 300ms after the last event occurs.

Conclusion

To summarize, delaying your function calls which occur during frequent events can significantly decrease loading times. Making this slight change to your code can improve the performance of your application by multiple folds. This is the power of Debouncing.

💖 💪 🙅 🚩
ishjotsb
Ishjot Singh

Posted on September 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related