Use TypeScript React to debounce click event functions
P粉032649413
2023-08-27 10:33:19
<p>I'm trying to implement the lodash debounce function on the onclick function to avoid multiple clicks on the button. The solution I came up with is this: </p>
<pre class="brush:php;toolbar:false;">function saveForm() {
//Do some operations here
}
<Button onClick={debounce(() => saveForm, 1500, {
maxWait: 2000 })}>
save
</Button></pre>
<p>I see many examples of performing debounce on a function outside of the return, and then using that debounced function in onclick. Is it wrong to perform debounce (inline) directly on the button element? </p>
In terms of good coding practices, you should avoid putting too much business logic in JSX. Just extract your
onClick
handler outside of JSX.Secondly, you don't want to return to
saveForm
after deshaking. Instead call it. So replace() => saveForm
withsaveForm
.You can also use the
useCallback
hook. I leave the best practices for usinguseCallback
hooks up to you to explore if needed.