Home > Mobile >  arrow function in jsx
arrow function in jsx

Time:06-23

const MyComp = () => <button onClick={() => nagivate('/')}>home</button>

I have code above where I put arrow function inside my onClick handler. My colleague asked me to do this instead:

const MyComp = () => {
   const handleClick = () => nagivate('/')
   return <button onClick={handleClick}>home</button>
}

What is the point of it? he argue we can have performance issue. I'm confused.

CodePudding user response:

Both versions are equivalent. The handleClick function will we redefined on every render. To improve performance use useCallback(() => nagivate('/'), [nagivate]). Then the function will only change if the navigate function changes.

CodePudding user response:

If you pass anonymous function as event handler it will cause function recomputation(recreation) on each rerender, thus forcing element which exposed you event to also rerender since it "thinks" that new handler is passed because of new function reference of your anonymous event handler. If function recomputation affects your UI performance I suggest you to wrap handler in useCallback and like that you will have stable reference of you handler. At the end I disagree with you colleague that this(one simple button) will have impact on you performance, if it does it means that your upper levels are the ones that needs optimizations. It is cleaner but in terms of performance, in this specific case, almost no difference.

  • Related