0

In the React docs, the constructor functions of class components contain lines where this is explicitly bound for event handlers e.g. in the docs for handling events

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(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  ...
}

When using arrow functions the binding is no longer required i.e

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
  }

  handleClick = () => {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
  ...
}

Is there a good reason for preferring the explicit binding over the arrow functions?

1

Unless you are using bind(this) and/or arrow functions directly in the render function there are no performance differences and the reasons why it's present in the documentation is most likely purely historical.

Choose one style and adhere to it. Stay consistent, do not mix both of them and you will be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.