Ways to implement Debounce | Shreya

Ways to implement Debounce

media

Refer to the previous post to understand what is debounce and when to use debounce.

In this thread🧵, we'll implement debounce in 2 different ways

...

From scratch(JS)

The general idea here is to start with 0 timeout, then if the debounced function is called again, reset the timer to the specified delay. In case of timeout, call the debounce function.

Thus every call to a debounce function resets the timer and delays the call. Let’s dive in and see what a debounce looks like-

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

Using Lodash

Another way to implement debouncing is using lodash. Lodash provides a debounce method that we can use to limit the rate of execution of the handler function. Just wrap the callback function with the debounce method and provide the amount of delay we want between two events.

import { debounce } from 'lodash' const debouncedSearch = useCallback( debounce(val => { onSearch(val) }, 750), [onSearch] )

But there is a problem with useCallback here, you get the following error:

media
Error: React Hook useCallback received a function whose dependencies are unknown. Pass an inline function instead react-hooks/exhaustive-deps

useCallback expects an inline function. Handing it the returned function from a debounce or throttle doesn't cut the mustard. Why? The ESLint rule can't figure out what the exhaustive dependencies should be. How do we fix this?

To remove this error, use useMemo instead:

import { debounce } from 'lodash'; const debouncedSearch = useMemo( () => debounce( (val) => { onSearch(val) },750), [onSearch] );

Tagged users
editor-img
Aakash Bhardwaj
@24-randene
Now your chickens are coming home to roost