Using Arrow Functions to avoid binding `this` in React
Arrow functions were introduced in 2015 at ES6 and have since become the most popular ES6 feature. If you have no knowledge on arrow functions I recommend checking out the MDN reading to see what they can do and read up on syntax.
Moving on I will specifically focus on arrow functions and their usage with this in React. Arrow functions make your code look cleaner and more presentable but on top of that there are more reasons to use them in React.
To begin I’ll give a quick definition of what this is in React. this in general refers to a JavaScript element depending on the scope or context of its use. So in React, when we define classes we use methods inside those classes to refer to attributes such as state and props. For our methods to have access to this.state and this.props we need to bind the React component this context to those methods. Binding this to the class methods enables us to access props and state for the component with this.props and this.state. A benefit of using arrow functions is that this is already bound to that function so we don’t need to specify that anywhere else.
Use arrow functions to avoid binding `this` to methods:
Usually when you want to access this inside a class method you would need to bind it to your method like so:
Binding this to handleClick in the constructor allows us to use this.setState from Component inside handleClick. Without this binding, this is re-scoped for handleClick and therefore cannot be used with the setState method.
However using arrow functions makes this whole process unnecessary and leaves your code looking much nicer:
Here you can see 3 lines of code have been cut out just from changing that one function. It may not seem like a huge deal for this example but in a huge app with many components it will definitely make a difference. The great thing about an arrow function is that this means the same thing within the function body as it does outside of it. Which means that if you use arrow functions within your component’s render, they can access this and this.setState. Doing this I can call handleClick in just one line.
As you can see using arrow functions in class components can end up saving you lines of code and time which is a win win situation. Properly understanding and knowing how to use arrow functions can make your life easier when dealing with this . Please let me know if you have any questions!
Now go ahead and use your arrows. #bigmoneymoves
Resources: