DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
jivkojelev91 profile image
JivkoJelev91 • Edited

Why not just:

export const debounce = (func, wait) => {
  let timeout;
  return function(...args) {
    const context = this;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      func.apply(context, args);
    }, wait);
  };
};
Enter fullscreen mode Exit fullscreen mode

Now you can use this debouce in other hooks.

Collapse
 
johanse7 profile image
johanse7

how do you make the call debounce function ?

Collapse
 
dextermb profile image
Dexter Marks-Barber
const onChange = debounce(event => setQuery(event?.target?.value))
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
rohan2734 profile image
rohan2734 • Edited

nope not working , geting the state value as undefined

Thread Thread
 
dextermb profile image
Dexter Marks-Barber

Are you able to show your code for the event handler and how you trigger the call?

Thread Thread
 
rohan2734 profile image
rohan2734

i have triggered the call in the same way, but it is not working at all ,and state is undefined