React Quick Tip: Use Class Properties and Arrow Functions to Avoid Binding `this` to Methods

dave.js
dave.js
Jan 29, 2018 · 2 min read

When you want to access this inside a class methods of your React component, you need to bind it to your method:

class Button extends Component {
constructor(props) {
super(props);
this.state = { clicked: false };
this.handleClick = this.handleClick.bind(this); } handleClick() {
this.setState({ clicked: true });
}
render() {
return <button onClick={this.handleClick}>Click Me!</button>;
}
}

Binding this to handleClick in the constructor allows us to use this.setState from Component inside handleClick. Without this binding, this is re-scoped for handleClick and loses context of the component’s setState method.

But this is completely unnecessary, extra code!

You can clean up this ugliness by using some new ES6+ features. Here is the same component, rewritten using class properties and arrow functions to avoid binding this to handleClick:

class Button extends Component {
state = { clicked: false };
handleClick = () => this.setState({ clicked: true }); render() {
return <button onClick={this.handleClick}>Click Me!</button>;
}
}

Note: You must have transform-class-properties enabled in your own Babel config in order to use class properties. If you’re using Create React App, this is already enabled for you.

Why Does This Work?

This works because of two reasons:

  1. Arrow functions, by their nature, do not re-scope this, so we don’t need to bind this in the class constructor.

Bonus Tip

Notice in the second example, I defined state as a class property as well, negating the need for a constructor.


Please click 👏 button below a few times to show your support! ⬇⬇

Thanks! Don’t forget to follow Quick Code below.

Find out Free courses on Quick Code for various programming languages. Get new updates on Messenger.

Quick Code

Find the best tutorials and courses for the web, mobile, chatbot, AR/VR development, database management, data science, web design and cryptocurrency. Practice in JavaScript, Java, Python, R, Android, Swift, Objective-C, React, Node Js, Ember, C++, SQL & more.

dave.js

Written by

dave.js

I’m an artsy software engineer. I write about JavaScript/React, and sometimes my opinions about other things. ¯\_(ツ)_/¯

Quick Code

Find the best tutorials and courses for the web, mobile, chatbot, AR/VR development, database management, data science, web design and cryptocurrency. Practice in JavaScript, Java, Python, R, Android, Swift, Objective-C, React, Node Js, Ember, C++, SQL & more.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade