I recently built an anime app that fetches details about animes from an external API. The project had an input field where you could type in the name of an anime to search for. The text entered in the input field was then used to query the API for animes matching the input. The input field was to use “instant search” mechanism. This meant that users were not required to hit enter or press a button for the search to occur. To prevent making a call to the API on every keystroke, I had to debounce the queries made to the API.
According to a dictionary definition, debounce is "To remove the small ripple of current that forms when a mechanical switch is pushed in an electrical circuit and makes a series of short contacts."
In programming, debouncing is a practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. This is done to limit the rate at which a function gets invoked.
We would be using Create-React-App to bootstrap our project.
We would be using Material-UI, Axios as additional dependencies. We would be getting the anime details from Jikan Apiary
This is our initial application setup. The issue that arises from this is that the request to the API is made on every keystroke entered by the user. To debounce the input and ensure it only occurs after a stipulated time, for example, every 250ms, we would be using the setTimeout function. The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
To prevent our setTimeout function from being redefined on every render, we would use useRef to create a reference that would be persisted across every render. We would also ensure to clear our timeout to prevent memory leaks.
We have added our API call inside a timeout callback. Our request to the API would now occur after 250ms. On every keystroke made by the user, we clear the timer and extend it by another 250ms. If the input field is empty, we return from the function and do not make a call to the API. The call to the API now only happens 250ms after the user has stopped typing, instead of on every keystroke.
And that's it, we are done. We have been able to create an instant search input field that delays by 250ms after the user finishes typing before making an API call.
The full source code can be found here.