What is debouncing?
Debouncing is a pattern or a technique to restrict the calling of a time-consuming function frequently, by delaying the execution of the function until a specified time to avoid unnecessary CPU cycles, and API calls and improve performance.
Why you should use the debouncing technique?
While you developing the web app majorly when you build a customer-facing web app you need to be very performant your website should not freeze anytime while the user is doing anything on the browser. You can use this technique and improve the performant of your web page.
If you go to any application where the search function is there which calls the API call like Youtube, Flipkart, Amazon, etc. It does not make API call in every key press.
Let's understand debouncing with the example of a search query suppose you have an input element that gets some data when you type something. Let's say you type something like a mobile name that returns some data.
But there is a catch here, Let's say you type something like "iPhone".If you type the first character that is 'i' you send the request to the backend server. Then you type another character that is 'p' and you will send another request to the server, and so on.
This calls the API so many times, and in turn, overuses the requests. So to prevent this we have a feature called debouncing.
Implementing debouncing using React
You can implement the debouncing using React. We always call the API call inside the useEffect hook with some dependency here the dependency is that searchQuery whenever the search query changes or when you type something in search input then the useEffect will be called. In the use effect hook, have setTimeout has callback function whenever the search has some input then it will call the setSuggestion function which will set suggestions as per the input, else it will call the getSearchSuggestions and we will set the timer with 200ms.
And now in the getSearchSuggestion function calls the API.
We will also need to destroy the instance of useEffect using return and followed by clearTimeout every Time it finishes.
const [searchQuery, setSearchQuery] = useState("");
const [suggestions, setSuggestions] = useState([]);
const [showSuggestions, setShowSuggestions] = useState();
const searchCache = useSelector((store) => store.search);
useEffect(() => {
console.log(searchQuery);
const timer = setTimeout(() => {
if (searchCache[searchQuery]) {
setSuggestions(searchCache[searchQuery]);
} else {
getSearchSuggestions();
}
}, 200);
return () => {
clearTimeout(timer);
};
}, [searchQuery]);
const getSearchSuggestions = async () => {
console.log("API call" + searchQuery);
const data = await fetch(YOUTUBE_SEARCH_API + searchQuery);
const json = await data.json();
console.log(json[1]);
setSuggestions(json[1]);
};
First, Create a state using the useState hook in React
const [searchQuery, setSearchQuery] = useState("");
We need to set the data in the search query state when we type something, using the onChange event handler.
<input type="text" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)}/>
useEffect hook with some dependency here the dependency is that searchQuery whenever the search query changes or when you type something in search input then the useEffect will be called.
useEffect(() => {
}, [searchQuery]);
In the use effect hook, have setTimeout has a callback function whenever the search has some input then it will call the setSuggestion function which will set suggestions as per the input, else it will call the getSearchSuggestions and we will set the timer with 200ms. We also need to destroy the instances of the useEffect hook using return followed by the clearTimeout every time it finishes.
useEffect(() => {
console.log(searchQuery);
const timer = setTimeout(() => {
if (searchCache[searchQuery]) {
setSuggestions(searchCache[searchQuery]);
} else {
getSearchSuggestions();
}
}, 200);
return () => {
clearTimeout(timer);
};
}, [searchQuery]);
Now the getSearchSuggestions function calls the API.
const getSearchSuggestions = async () => {
console.log("API call-" + searchQuery);
const data = await fetch(YOUTUBE_SEARCH_API + searchQuery);
const json = await data.json();
console.log(json[1]);
setSuggestions(json[1]);
};
And we are done, Now type something like "iPhone"
Winding up
Now you know how and why to use the debounce function. So simple and easy right?
Now, if we type any search query in the input, it will display after 2 seconds just when we stop changing the input. And we used debouncing to do this.
There are multiple applications of debouncing. We can use it to keep from hitting our API over and over. And we can use it to make sure the form data gets submitted only once, even if we click the submit button multiple times.