Reputation: 33
Looking at the react tutorial it explains that when we set event listeners, we generally have to bind the functions context, like is done here
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
I understand this, because unless we bind context to the this.handleClick
function we have no guarantee of what value this
will actually hold when we call this.setState
within the handleClick function. However, the tutorial goes on to state that we would not have to bind context to the handleClick function if we replaced
<button onClick={this.handleClick}>
with <button onClick={() => this.handleClick}>
How come the correct this
context is automatically bound when we use an arrow function?
Upvotes: 1
Views: 138
Reputation: 21638
You don't need to but arrow functions keep context of this
as the object that defined them where traditional function context this
as the object that calls them. You can use normal functions as long as they don't call this or keep a reference to this with a variable link const self = this
and use self instead of this.
Why is this the case? Because they designed it to be so.
Upvotes: 1