Debouncing in React

Rajitha Sanjayamal
2 min readNov 19, 2022

Debouncing is a technique to control how many times we allow a function to be executed over the time. Simply It delays (rate limits) execution of the function.

Assume, user types something in search element then we have to get data form the API.

Normally, It will make API request for each and every inputs. If user types 10 characters then it will make 10 API requests.
Oh my god!…. There are so many API calls. If thousand of users interact with application, API will be hurt.

So prevent this, Debouncing comes into the picture. Let’s see how to implement it without using 3rd party libraries.

Imagine, we are implementing application for searching cars detail.

Step 01 : Add utils folder and FunctionUtils.js file. (src/utils/FunctionUtils.js)

Step 02 : Put below code snippet into FunctionUtils.js file.

export const debounce = (func, delay) => {
let timmer;
return function () {
const context = this;
const args = arguments;
clearTimeout(timmer);
timmer = setTimeout(() => func.apply(context, args), delay);
};
}

Step 03 : Add index.js file into utils folder and re-export FunctionUtils using index file.

export * from './FunctionUtils'

Step 04 : Apply the debouncing function.

import React, { useCallback } from "react";
import { debounce } from "../utils";

export function Cars(props) {

const onSearchCars = (event) => {
const value = event.target.value;
if (value) {
// Make API request here
console.log(`Calling API ${value}`);
}
};

const handleOnChange = useCallback(debounce(onSearchCars, 600), []);

return (
<div>
<input type="search" onChange={handleOnChange} />
<div>{/* display list of cars */}</div>
</div>
);
}

See how it works,

Now, It doesn’t make API request for each and every inputs.

If we type any search query, It will make API request after 0.6 seconds just when we stop changing inputs.

Ooh…! It improves the performance. So simple and easy right?

--

--