Skip to content
Today's Tech Byte: Implementing advanced debouncing and throttling with Refs

Today's Tech Byte: Implementing advanced debouncing and throttling with Refs

Posted on:November 23, 2023

In this chapter, we will learn what debouncing and throttling are and how to implement them in React using Refs.

Debouncing and throttling

Debouncing is a technique that allows us to delay the execution of a function until a certain amount of time has passed since the last time the function was called.

For example, if we have a search input that calls a function to fetch data from an API every time the user types a character, we can use debouncing to delay the execution of the function until the user stops typing.

Throttling is similar to debouncing, but instead of delaying the execution of a function until the user stops typing, it delays the execution of a function until a certain amount of time has passed since the last time the function was called.

Lodash has a debounce and throttle function that we can use to implement debouncing and throttling, feel free to check out the documentation for more details.

Debouncing and throttling in React

For React, we can not just use the debounce and throttle functions from Lodash.

Let’s take a look at the following example:

const [value, setValue] = useState("");

const handleChange = e => {
  setValue(e.target.value);
  debounce(() => {
    // fetch data from API
  }, 500);
};

It looks like it should work, but it doesn’t. The reason is that every time the component re-renders, the debounce function will be called again, and the timer will be reset.

To solve this problem, we can use Refs.

You can find the code for the debounce and throttle hooks here

If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.

P.S. this post is inspired by the book, but it’s not a summary of it. I’m just sharing what I learned from it. If you want to learn more about React, I highly recommend you to read it.