How do you perform debounce in React.js?
I want to debounce the handleOnChange.
I tried with debounce(this.handleOnChange, 200)
but it doesn\'t
for throttle
or debounce
the best way is to create a function creator so you can use it any where, for example:
updateUserProfileField(fieldName) {
const handler = throttle(value => {
console.log(fieldName, value);
}, 400);
return evt => handler(evt.target.value.trim());
}
and in your render
method you can do:
the updateUserProfileField
method will create a separated function each time you call it.
Note don't try to return the handler directly for example this will not work:
updateUserProfileField(fieldName) {
return evt => throttle(value => {
console.log(fieldName, value);
}, 400)(evt.target.value.trim());
}
the reason why this will not work because this will generate a new throttle function each time the event called instead of using the same throttle function, so basically the throttle will be useless ;)
Also if you use debounce
or throttle
you don't need setTimeout
or clearTimeout
, this is actually why we use them :P