Using a Debounced Callback in React

Banky Adebajo
The Startup
Published in
3 min readSep 12, 2020

Debouncing is a really useful tool that software engineers should be familiar with. Today, I will be creating a React hook that should hopefully solve most of your debouncing needs.

Before I get started, debouncing is a term that gets thrown around quite a bit in software systems. The term originates from electrical systems that don’t cleanly switch from “on” to “off” and change more like this

An example of a noisy signal that needs debouncing
Noisy signal that needs debouncing

When making the switch from off to on, the signal “bounces”. So “debouncing” is just cleaning up this noise. The system debounces this signal by only reacting to the new state when the signal has stayed the same for a certain minimum amount of time.

In web development, this idea is also quite useful especially when dealing with user interaction. As an example, we could attach an event listener and do some action when the user resizes their browser window. However, this action will get called so often that it may end up blocking the main Javascript thread and bringing the application to a shuddering halt.

Another example is hitting an API on type events. This is useful for creating an auto search input similar to what you would find on Google

Hitting an API with every keystroke will result not only in performance issues locally, but when using a public API like the Spotify Web API you will hit limits very quickly. To resolve issues like this when using React, I have created a debounce hook that looks something like this

Firstly, we create a timeout ref that will be used to determine whether it is time to actually fire the function. A ref is used here so that it can be updated without re-rendering the component that this hook is used in.

Next, every time the function that is returned from the hook is called, the existing timeout is cleared and a new one is created. If the function hasn’t been called for the wait period, then the later function will get called. This clears the timeout and actually calls the function that was passed in. Here is a working example of this code being used

In this example, a fake API is used that just returns the text inputted but capitalized. When typing in the text field, the output isn’t updated until 1 second after the user stops typing. This is extremely powerful when hitting an actual API to perform type to search without burning through API limitations. The wait period can be adjusted easily by passing in a different value to the useDebouncedCallback call.

Hopefully this is useful for anyone trying to figure out how to debounce with react. A hook like this can easily be refactored to work with pure javascript and I will be writing a separate tutorial to do just that soon!

Cheers

--

--