score:13

Accepted answer

the debounced function is getting recreated on every re-render.

you will need to wrap it in usecallback which will hold the same reference unless one of the variables inside the dependencies array change

const changefilterdebounced = usecallback(
  debounce(value => console.log(value), 3000, true),
  []
)

score:1

as you're using a functional component, all the functions defined will be reinitialized on each render, ie creating a new debounced function each time.

the possible workaround is to use usememo and usecallback along with it so that the reference of function does not change on each render.

const changefilterdebounced = debounce(changefilter, 3000, true);

can be changed into:

const changefilterdebounced = usememo(() => debounce(changefilter, 3000, true), [handlechange]);

and wrap handlechange with usecallback like:

const handlechange = usecallback(e => {
    let { value } = e.target;
    setsearchstring(value);
    changefilterdebounced(value);
}, []);

the empty dependency array as the second argument of usecallback was provided, so that its ref will be the same till the component unmounts.

hope this helps.

score:1

debounce is weird for that it bases on closure which may leads many strange things. closure means the function keeps the variables alive even if it returns. so it seems like there is an instance after invoked.

as in your case, you typed three chars. and everytime you typed, the setstate got called which leads that react renders your component and produces a debounced function. every debounced function works separately. that is why you got three logs.

try using usecallback to make sure that you always use the first debounced function.


Related Query

More Query from same tag