To optimise browser performance as well as keep up with user experience deliverables, there are few techniques, one of which is debouncing.
A very fine example for this would be any search bar. When you type a word in search bar with every letter it shows new recommendations.
From the surface the trick here must be making an API call every time somebody enters a letter to fetch desirable options according to latest input.
A better way to do this is through debouncing,
We set a
threshold
for a time period, can be 5s or .05 sec.Every time this threshold timer expires, we make an API call to get data best matching the input.
Clear the timer and reset
Code:
<input
className="search-bar"
onChange={ hecticSearchHandler }
/>
function hecticSearchHandler(...args){
/* capture the search query entered by customer */
const { value } = args[0].target;
/* Make an API call with search query */
getSearchResults(value);
}
Reusable function code:
const optiSearchHandler = debounceFunc(searchHandler, 500)
const debounceFunc = (func, delay) => {
let timer;
return function(...args) {
const context = this;
clearTimeOut(timer);
timer = setTimeOut(() => {
func.apply(context, args);
}, delay)
}
}
Watch this video for clarity: Debounce interview ques
Top comments (2)
In React 18 you do not have to debounce anymore unless you really only want something to happen after a very specific amount of time. Otherwise you can use the new
useDeferredValue
hook: reactjs.org/blog/2022/03/29/react-...Sounds interesting.
Will definitely check this out!