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?

asked Oct 2, 2017 at 12:49

1 Answer 1

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.

answered Oct 2, 2017 at 13:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.