Here are two examples of writing an ES6 class method:
The first uses non-fat arrow, or concise method syntax--whatever it is correctly called:
class Test extends Component {
handleClick() {
return 'clicked'
}
}
The second uses fat arrow syntax:
class Test2 extends Component {
handleClick = () => {
return 'clicked'
}
}
Should I always prefer to write using fat arrow syntax?
One thing I notice is you could use implicit return which could shorten code.
In most examples I see of people writing constructor()
and render()
methods in React, they do not use fat arrow syntax for those, but they do for all other class methods.
Why is this?
I am guessing the answer will have something to do with the this
keyword since it is fairly intrinsic to classes and the context-preserving nature of fat arrows, but how does this relate to React and fat arrow syntax on class methods? The only case I can think of is that you might be able to avoid binding in the constructor for some cases depending how the class method is called later.
I would appreciate a scientific answer or a list of cases where a distinction is important.
Consider the render function below
render() {
return <div onClick={this.handleClick} />
}
When handleClick
is defined as an arrow function, the function is executed when the click event is fired. Otherwise it's run at the same time as render
.
Should I always prefer to write using fat arrow syntax?
It depends on how/from where you need to call your function. For event handlers, arrow functions are convenient because as you state the component's this
is accessible and you also need to pass in the function as opposed to its output.
If you don't need to access the component's this
or pass your function, then an arrow function is not necessary.