Beware arrow function overuse in React

Beware arrow function overuse in React components

There are lots of things to love about ES6 arrow function. The syntax is short and sweet and there’s no binding of this or arguments. Take the extremely simple function double below for example.

1
2
3
const double = function (a) {
return a * 2
}

Now here’s it is written as an arrow function using concise syntax.

1
const double = a => a * 2

You’ll note that the brackets around any single argument are optional, the curly brackets are optional, and the return is implied.

The downside

While arrow functions are great for the most part, it may be worth considering how specific use cases could lead to performance impacts in React. This is especially true when an arrow function is defined in a component’s render method. Since each time render is called a new instance of the function is created, even a shallow compare as is done in shouldComponentUpdate of a pure component would evaluate to false & cause any lower level components to render anew.

While the performance hits will be neglibile in most cases, it’s probably worth keeping in mind that arrow functions are not always your friend and avoid using them in the render function if not needed. For more tips on how get around this issue altogether, see Handle events by arrow functions in React app.

Jenny Sharps
Software Engineer