Using Arrow Function Correctly in React to Increase Performance

In a React component, we sometimes use the code like this:

handleChagne(event){
// Do something...
}
...
/* In the render method */
<input onChange={event => this.handleChagne(event)} />

This way can let us enjoy the feature of automatic binding “this” to the function. However, this method will cause React create a new function every time when the component is rendered, which may reduce the performance a great deal.

One way to avoid this is to define an arrow function in the React class and pass it to the input element. The code should be looked like this:

handleChange = event => {// Do something...}
...
/* In the render method */
<input onChange={this.handleChagne} />

It will give you a syntax error when you try to compile it. In order to run the code like this in a React app, we have to use Babel’s “babel-plugin-transform-class-properties” plugin. This plugin will help us transform properties to functions. Two steps list below are necessary for using this plugin.

  1. Running “npm i babel-plugin-transform-class-properties — save-dev”
  2. Adding “plugins”: [“transform-class-properties”] in your .babelrc file.

Now, we can enjoy the automatic binding “this” and higher performance.