-1

I heard in an Udemy ReactJS class, using an arrow function for an onClick handler will cause performance issue and unnecessary render for the component:

return (
  <button onClick={() => this.doSomething()}>

or what about

return (
  <Foo onClick={() => this.doSomething()}>

Is it true? I don't quite see how it can cause unnecessary re-render, as the whole subtree from this component and down should need to be re-rendered anyway.


The recommendation is to use one of the following:

1) use

return (
  <button onClick={this.doSomething.bind(this)}>

2) in the constructor

this.doSomething = this.doSomething.bind(this);

3) in the class definition, use arrow function instead:

const doSomething = () => {   };
Jeremy L
  • 3,770
  • 6
  • 41
  • 62
  • 1
    Does this answer your question? [Correct use of arrow functions in React](https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react) – Hoyen Feb 25 '20 at 15:23
  • I also made the question: ` – Jeremy L Feb 25 '20 at 15:26
  • so I think the issue is not about re-rendering. It is about updating the actual DOM... – Jeremy L Feb 25 '20 at 15:40
  • so even `onClick={this.doSomething.bind(this)}` is not good, because it is creating a new function every time – Jeremy L Feb 25 '20 at 15:43

1 Answers1

0

becuase in javascript Functions are First class objects, so this function

<button onClick={() => this.doSomething()}>

when a re-render occures due to a state change, the render method will be called again. so {() => this.doSomething()} will be created again, and react comprase the object references. although it seems the same to you, its not for javascript and react, becuase {() => this.doSomething()} will be created again, since its an object, and its reference is a different one from the one in the previous render.

Ahmed Khattab
  • 2,645
  • 2
  • 13
  • 19
  • so it is a new function... so I think the issue is that the button is the actual DOM needs some maintenance because now the listener is a different function... React needs to update the actual DOM, that's the issue – Jeremy L Feb 25 '20 at 15:42
  • yes, its a completely new object created in memory – Ahmed Khattab Feb 25 '20 at 15:44