userden
userden

Reputation: 1683

Using bind(this) in React

Can I use any of these options? Do they all work the same way? I'm using ES6.

onChange={this.makeChange.bind(this)}

onChange={() => this.makeChange()}

constructor(props) {
  super(props);
  this.makeChange = this.makeChange.bind(this);
}

Upvotes: 3

Views: 179

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16846

Yes, you can use all three. Even though they behave the same, they have different performance implications.

Binding the function in the constructor is the best option performance-wise, because the function is only created once when the component is instantiated. While with the other solutions a new function is created whenever the component (re-)renders. This will cause child components to also re-render, because their props have changed.

You can read more about this in the official React docs: https://facebook.github.io/react/docs/handling-events.html


Personally, I prefer the following syntax using class properties (this is only available if you're using TypeScript or a Babel plugin):

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

This option is also explained in the React docs.

Upvotes: 3

Related Questions