Binding this in React

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 this to 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 rendermethod.

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.


You can find the original article I posted on Medium here.

To view or add a comment, sign in

More articles by Raoul George

  • Anatomy of a frontend tech interview

    There are a plethora of articles on what to expect in a frontend tech interview. But not too many opinions on how…

    4 Comments

Others also viewed

Explore content categories