Use TypeScript React to debounce click event functions
P粉032649413
P粉032649413 2023-08-27 10:33:19
0
1
415
<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>
P粉032649413
P粉032649413

reply all(1)
P粉744691205

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 with saveForm.

function saveForm() {
//在这里执行操作
}

const debouncedClickHandler = debounce(saveForm, 1500, {maxWait: 2000})

<Button onClick={debouncedClickHandler}>保存</Button>

You can also use the useCallback hook. I leave the best practices for using useCallback hooks up to you to explore if needed.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!