The JavaScript this Keyword And Its Use in ReactJs

Note: This post is work-in-progress learning-note and still in active development and updated regularly.

The this key word is widely used in ReactJs. While deep diving this keyword, I thought to take a brief detour to explore how this keyword is used in the ReactJs.

Use of this keyword in JS very confusing. In a previous learning-note post Understanding of this keyword in different context is discussed. In this brief learning-note post, how and where this keyword is commonly applied ReactJs application is explored.

Prerequisite

It is assumed that use of this keyword in different context for example, global, in function, in constructor operators, in object methods and arrow functions. A brief overview is discussed in Understanding of this keyword learning post.

A brief overview of Functions

There are following three types of functions (adapted from amitai10’s GitHubGist post):

1. Constructor function: Constructor is a function that is used to create new object with the same prototype using the new keyword.

//create constructor function
function Greeting() {
  this.msg = 'Hello World!';
}
//create new object instance
var newGreeting = new Greeting();
//invoke object instance
console.log(newGreeting.msg); //OUTPUT => Hello World!

In the example above, this (line 3) refers to object Greeting (line 2).  When constructor object newGreeting.msg is invoked (line 8), the this in this.msg (line ) refers to "Hello World!" and newGreeting object with msg property refers to the Hello World! value (line 8).

2. Function function: Function in JS is a function and unless not a property of an object.

function Greeting() {
  console.log(this); // undefined
}
//strict mode
function Greeting() {
 'strict mode';
  console.log(this === window); // true
}

In the example above, this refers to undefined or global (window) in browser.

3. Method function: A method is a function and its an property of an object. The MDN states that “when a function is called as a method of an object, its this is set to the object the method is called on“. Revisiting example from Understanding this Keyword in JavaScript below:

//expression function
const helloWorld = {
  greeting: "Hello World!",
  // define method
  msg() {
    console.log(`${this.greeting} We are live.`);
  }
};
//invoke
helloWorld.msg(); // OUTPUT => Hello World! We are live.

In the example above, helloWorld object (line 2) has msg() method defined inside body (lines: 5-7). When helloWorld.msg is invoked (line 10), value of this inside msg() method (line 10) refers to helloWorld object where it is bound.

How this is Applied in React

In ReactJs application, components classes which are derived from React.Component are used. In the following example from amitai10 GitHubGit post a MyComponent component renders a form submit on onSumit() method that change the state of MyComponent.

//source:https://gist.github.com/amitai10/adb66d6faa714e8c3cdb94946bb98356
// #how-to-imply-it-in-react

import React, {Component} from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }
  onSubmit() {
    this.props.submit(this.state)
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        ...
      </form>
    );
  }
}
export default MyComponent;

In the example above, this is bind the class methods onSubmit() and render() which enables to access props and state for the component with this.props and this.state. There are lot of this (lines: 10, 12, 16) and their understanding is key to understanding and writing react components.

With Arrow function,  the binding of this is not necessary because this is already bound to the function.

//source:https://gist.github.com/amitai10/adb66d6faa714e8c3cdb94946bb98356
// #how-to-imply-it-in-react

import React, {Component} from 'react';

class MyComponent extends Component {
  onSubmit = () => {
    this.props.submit(this.state)
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        ...
      </form>
    );
  }
}

export default MyComponent;

In the example above, this is bound to the onSubmit() method (line 8). By combining arrow function and public class fields offers much cleaner approach to define react components.

ReactJs Does Not Treat this Differently

Previous examples demonstrate that this keyword is encountered more often in ReactJs because it make use of classes, constructors to create react components. These components also contain several methods attached to them. In addition, the components also contain their own state and inherit their properties to children components. The this keyword is used to refer all these components and since there are lot of uses of this to refer different component depending upon the context. Keeping track of every use of this gets really confusing!

Wrapping Up

This learning-note posts was prompted by previous post on use of this keyword. In this post overview of JS function types and use of this keyword in ReactJSs component was shown. A quick glance of ReactJS component reveals importance of understanding of JS fundamentals. To quote Robin Wieruch: “Build things yourself before you dive into the next topic. Programming is about getting your hands dirty and not only reading and watching tutorials.

Interesting article: JavaScript fundamentals before learning React by Robin Wieruch | www.robinwieruch.de

Useful Resources and Links

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.