Binding this in React

React does not automatically bind this in ES6 classes.
From their docs:
In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don’t automatically bind
thisto the instance.
Render Binding
So in order to get around this, we learned to love bind.
class TestComponent extends React.Component {
handleClick(event) {}
render() {
return (
<div>
<input type="button" onClick={this.handleClick.bind(this)} />
</div>
);
}
}The problem with this way of doing things is that a new function is called every time this component re-renders. It also looks a little clunky when we bind in the click handler.
Arrow Functions in render
A less verbose way to do this is by using arrow functions in your render method.
class TestComponent extends React.Component {
handleClick() { }
render() {
return (
<div>
<input type="button" onClick={() => this.handleClick()} />
</div>
);
}
}However, although the syntax is more succinct, we still suffer from the same problem that a new anonymous function is created every time the render method runs.
Constructor Binding
To get around the performance problems with directly binding in the handler, we can instead bind this to the handler in the constructor.
class TestComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick.bind(this);
} handleClick() { }
render() {
return (
<div>
<input type="button" onClick={this.handleClick} />
</div>
);
}
}
We can avoid the performance issues using this method. But we will face issues with scalability. As we need a separate bind for each method, once our component becomes a little more complex, the constructor will be filled with a ton of bind statements.
Arrow Functions in class
To get around the scalability problems with the other methods, we can use arrow functions as class properties.
class TestComponent extends React.Component {
handleClick = () => { }
render() {
return (
<div>
<input type="button" onClick={this.handleClick} />
</div>
);
}
}This solves the performance issues with the first two methods and the scalability problems with the 3rd option.
