Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React binding function

I have seen a lot of reactjs places where a function is called like below

onChange = {this.fileSelected}

whereas I have seen its usage like below as well

onClick={() => this.clearDisplay()}

I want to ask if they both mean the same or is there any difference and what to use when.

like image 541
Molly Christian Avatar asked Aug 17 '26 01:08

Molly Christian


2 Answers

If you use First:

onChange = {this.fileSelected}

It will only execute when onChange is called. If you want to bind this function then you have to declare it in the component class constructor like this:

constructor(props) {
    super(props);
    this.state = {
      // your state
    };
    this.clearDisplay = this.clearDisplay.bind(this);
}

The Second one:

onClick={() => this.clearDisplay()}

This defines an anonymous function but, does not call it. Only when onClick is fired is it called. However, in some cases using an anonymous function can cause performance issues. That anonymous function will be defined on every render - and if you have a component that is re-rendering very often it can hurt the performance of your application. If you are sure that the component will not be rendered often, an anonymous function should be fine for convenience.

like image 54
mitesh7172 Avatar answered Aug 18 '26 15:08

mitesh7172


onChange={this.fileSelected}

Is preferable because it is able to not cause unnecessary re-renders.

onClick={() => this.clearDisplay()}

When you pass an anonymous function like this it will actually be called on all instances of the class instead of the one that the event was triggered on.

From a high level in may seem like they have the same behavior but if you were to use the second method consistently through a large codebase the performance of your application would suffer.

This article goes more in depth on the issue:

https://medium.freecodecamp.org/why-arrow-functions-and-bind-in-reacts-render-are-problematic-f1c08b060e36

like image 23
23k Avatar answered Aug 18 '26 15:08

23k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!