Reputation: 800
I've been into a several React projects now, and I've notice in one project that every new method is not binded. What is the actual difference (if there's any)? Why bind if you could do it like the second example?
In the first case, the code has looked like this:
constructor(props) {
super(props);
this.state = { myState: false };
this.clickMe = this.clickMe.bind(this);
}
clickMe() {
this.setState({ myState: !this.state.myState });
}
The other example looks like this:
constructor(props) {
super(props);
this.state = { myState: false };
}
clickMe = () => {
this.setState({
myState: !this.state.myState
});
}
Upvotes: 0
Views: 333
Reputation: 1431
Arrow functions are great because they are faster and easier to write. In a small or medium size app there's not a tangible difference. You can use the arrow functions if you prefer and avoid the binding inside the constructor.
However, someone has decided to look at performance and side effects. So you can check these 2 links:
Upvotes: 2
Reputation: 15292
In constructure
,
this.clickMe = this.clickMe.bind(this);
Using bind
method you do explicit this
binding to provide context to clickMe
method.
ie. React Component Scope here
In short,you taking care to decide what is the invoking context scope (this
binding).
But with
clickMe = () => {
this.setState({
myState: !this.state.myState
});
}
Arrow function
take care for you do lexical scope binding of the React Component scope within which it is define.No need to use bind
If you dont use arrow function
,without bind
,your function will not get bind
ed to React Component scope.
Upvotes: 2