React Binding Patterns: 5 Approaches for Handling this

1-YJI4x0i0lJA110oRvjwNBw

Cory House:

There are at least five ways to handle the this context in React. Let’s consider the merits of each approach.

  1. Use React.createClass
  2. Bind in Render
  3. Use Arrow Function in Render
  4. Bind in Constructor
  5. Use Arrow Function in Class Property

Currently I’m mostly using Approach 4 (“Bind in Constructor”), but Approach 5 (“Arrow Function in Class Property”) looks like something to switch to after having read the post.

React Binding Patterns: 5 Approaches for Handling this

On a sidenote, ES2017+ will sport the Function Bind Operator (::) which acts a a shorthand for .bind(context).

// ES2015
this.logMessage = this.logMessage.bind(this);

// ES2017
this.logMessage = ::this.logMessage;

JavaScript ES7 Function Bind Syntax →

ES6 ES2015 Arrow Functions and this

Why you’d want to use arrow functions (next to them being shorter to type):

Arrow functions will maintain the this value of the enclosing context

Yes, this will work just fine:

function Wilto() {
	this.age = 32;

	setInterval(() => {
		this.age++;
		console.log( "I am now " + this.age + " years old");
	}, 3000 );
}

Whereas we used to do stuff like this:

function Wilto() {
	var self = this;
	self.age = 32;

	setInterval( function constantBirthdays() {
		self.age++;
		console.log( "I am now " + self.age + " years old");
	}, 3000 );
}

Source: A List Apart: On Our Radar: Self-Centered Edition →