I am trying to implement lodash debounce function on an onclick function to avoid multiple clicks on a button. The solution I came up with is as follows:
function saveForm() {
//do stuff here
}
<Button onClick={debounce(() => saveForm, 1500, {
maxWait: 2000 })}>
SAVE
</Button>
I have seen many examples where debounce is performed on a function outside the return and then just use that debounced function under onclick. Is performing debounce directly (inline) on the button element wrong practice ?
CodePudding user response:
If your component is re-rendered frequently, I think it could be replaced to useCallback
, but in normal case, I think your usecase looks okay.
CodePudding user response:
Instead of this you can you can add a loading state and based on that loading state disable the button.
CodePudding user response:
Actually we will validate within the form and save form outside the component. That gives clear valid input data and blindly save.
CodePudding user response:
Yea, @abdemirza right - better solution from UX perspective of view - it's to add loading state and disable button, when you async function do something.
It's not a mistake to use a debounce, but better use loading state
CodePudding user response:
As far as good coding practice is concerned, you should avoid putting too much of business logic inside JSX. Just extract your onClick
handler outside JSX.
Secondly, You do not want to return saveForm
after debounce. Rather call it. So replace () => saveForm
with saveForm
.
function saveForm() {
//do stuff here
}
const debouncedClickHandler = debounce(saveForm, 1500, {maxWait: 2000})
<Button onClick={debouncedClickHandler}>SAVE</Button>
You can also use useCallback
hook. I leave it up to you to explore the best practices for using useCallback
hook if you need to.