Home  >  Q&A  >  body text

Use TypeScript React to debounce click event functions

<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粉032649413P粉032649413441 days ago450

reply all(1)I'll reply

  • P粉744691205

    P粉7446912052023-08-28 00:00:43

    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.

    reply
    0
  • Cancelreply