How to use Debouncing in React?


posted by Akash Sarki on 31 January 2025
A debounce function can be used when you want to execute a function after a certain delay once the user stops trigerring it.
Let's learn how to use debouncing in React.
Implementing Debouncing in React:
We can implement debouncing with a combination of useEffect and setTimeout in React (For Functional components).
import { useState, useEffect } from "react";
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler); // Cleanup previous timeout
};
}, [value, delay]);
return debouncedValue;
}
// Usage Example
export default function DebouncedSearch() {
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 500); // Debounce with 500ms delay
useEffect(() => {
if (debouncedSearch) {
console.log("API call with:", debouncedSearch);
}
}, [debouncedSearch]);
return (
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search..."
/>
);
}
We start by creating a state variable "debouncedValue" in the above example.
We then create a "useeffect" hook, which will run when the component is initialised and when value or delay is updated.
Inside the "useeffect" hook, we declare a handler function which holds the "setTimeout" function, The setTimeout function will executes the code inside when the delay value is reached.
Suppose a user inputs a value and waits for the delay, The debounce useEffect will run saving the value in debouncedValue.
If the user inputs a value and types before the delay is reached, the cleanup function of useeffect will run clearing out all timeout functions and new setTimeout will be run saving the new value intil the delay time has reached.
Debouncing is a great way to handle re-rendering in react.
What to know about MUI? Read here.
Read More Blog posts

How to clone example template from Next JS repository?
This document teaches you to clone the example template from next JS official Github repository.

What is Material UI?
A popular React component library that provides a set of pre-designed, customizable UI components based on Google’s Material Design guidelines.