Class components in React

Neelakshi Lahiri
Last Updated: May 13, 2022

Introduction

We already know about components in React, but let’s have a quick look at what it is again.

Components in React are used to divide a user interface into independent components that can be handled easily and are reusable.

We also know that components are functional and class components, but do we know what class components in React are?

I guess not. 

For starters, Class components in React are the components used to track the state and lifecycle of components. For this reason, class components are also called stateful components. 

Now, if you already know about functional components, you are well aware that functional components can also be used to track the state and lifecycle of components. This leads us to wonder why we are using class components.

Before React 16.8, hooks did not exist, so using class components was the only way to track the state and lifecycle of a component. 

In this article, we’ll learn about class components in React and how they are used to track the state and lifecycle. 

Creating Class Components

When learning about class components, the first thing we must learn is how to create them. 

The general syntax to create a class component in React is:

class Animal extends React.Component 
{
    render() 
    {
          return <h2>HiI am an Animal!</h2>;
    }
}

 

As per the general rule of creating a component, its name must start with an uppercase letter. 

Also, the React.Component class is inherited to access React.Component’s functions, while the render( ) method is used to return HTML. 

Rendering Class Components

After creating a component, as shown above, we should learn how to use it, or in other words, how to render it. The syntax for rendering both functional and class is the same and is as follows:

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Constructors in Class Components

What is the first thing that comes to our minds when we hear the term “class”?

Objects and constructors, right, but then what is a constructor used for?

In any other programming language, a constructor is used to instantiate the objects, or in simple terms, assign values to variables corresponding to a particular object. 

Constructors in class components in React are somewhat similar. They are used to assign the component’s properties in an object which is called a state here under the Functional Components are Stateless Components section

For our better understanding, let us see an example of this.

class Animal extends React.Component 
{
    constructor()     //constructor 
    { 
          super();     //base class constructor
          this.state = {name: "Panda"};     //property is initialized
    }
    render() 
    {
          return <h2>I am a/an {this.state.name}!</h2>;
    }
}

 

Output:

Note: Props must always be passed to the constructor as shown below:

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
    }
    render() 
    {
          return <h2>I am a/an {this.props.name}!</h2>;
    }
}

 

ReactDOM.render(<Animal name="Panda"/>, document.getElementById('root’));

 

Output:

 

Props in Class Components

Prop (or properties) are like function arguments. So, they can also be used to initialize a component’s properties. 

If you have already read about functional components, you probably know how to use props. If you haven’t, though, don’t worry because the example below explains it all.

class Animal extends React.Component 
{
    render() 
    {
          return <h2>I am a/an {this.props.name}!</h2>;   //prop inserted
    }
}

 

 

//prop is initialized while rendering
ReactDOM.render(<Animal name="Tiger"/>,document.getElementById('root’));

 

Output:

Components in Class Components

A component can be referred to inside another class component, just like functional components. An example of this is shown below.

class Animal extends React.Component 
{
      render()
      {
            return <h2>I am a Panda!</h2>;
      }
}


 

 

class FavAnimal extends React.Component 
{
    render() 
    {
          return (<div>
                      <h1>What is your favourite animal?</h1><Animal />
                  </div>);
    }
}

 

ReactDOM.render(<FavAnimal />, document.getElementById('root'));

 

Output:

Class Components in Files

Do you remember why we were using components in React?

If you’re thinking about reusability, you’re right!

Now, another vital aspect of reusability is storing components in files and reusing them. To do that, we must first export a component following the syntax given below.

export default Animal;

 

Then, we can import the file and use it elsewhere, as shown below:

import React from 'react';
import ReactDOM from 'react-dom';
import Animal from './Animal.js';

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Output:

 

State of Class Components

As we already know, the primary use of class components in React was the access to the state and lifecycle of a component, but what do we mean by the state?

In simple terms, a state is a JavaScript object in React used to represent information about a component’s current situation. Its scope is inside a particular component, and it is used for internal communication inside a component.

Creating a State Object

We already saw the state being used in the constructor because the state object is always initialized in the constructor. 

We saw only a single property being initialized there, but did you know we can initialize as many properties as we want? 

Let’s see how in the example below.

class Animal extends React.Component 
{
    constructor(props)     
    { 
          super(props);  

          //property is initialized in state object  
          this.state = {name: "Polar bear", color: "White", age: "2 years"};   
    }
    render() 
    {
          return <h2>I am a/an {this.state.name}!</h2>;
    }
}

 

Using a State Object

After creating a state object, we would want to use it. The general syntax to use a state object is:

this.state.property_name

 

Let’s see a working example of this now. 

class Animal extends React.Component 
{
    constructor(props)     
    { 
          super(props);  

          //property is initialized in state object  
          this.state = {name: "Polar bear", color: "White", age: "2 years"};   
    }
    render() 
    {
          return <h2>I am a/an {this.state.name}. I am {this.state.age} old and am {this.state.color} in color</h2>;
    }
}

 

Output:

 

Changing the State Object

JavaScript is almost adding interactivity to a webpage. This can be done by changing the state of an object. Let us see an example where we’ll change the “age” on clicking a button.

class Animal extends React.Component 
{
    constructor(props)     
    { 
          super(props);  
          //property is initialized in state object  
          this.state = {name: "Polar bear", color: "White", age: "2 years"};   
    }
    
    changeAge = () => 
    {
          this.setState({age: "3 years"});
    }

    render() 
    {
          return (<div>
                        <h2>I am a/an {this.state.name}. I am {this.state.age} old and am {this.state.color} in color</h2>;
                        <button type="button" onClick={this.changeAge}>Change age</button>

    }
}

 

Note: State at first glance look similar to object but unlike object it can’t be updated by changing the value of a property we can only change state by the use of setState 

Lifecycle of Components

What does lifecycle mean in English?

A series of changes while something exists. 

Similarly, for components, its lifecycle specifies the behaviour of a component when it is being used. This will become more clear as we see the different lifecycle functions.

To start with, there are three phases in the lifecycle of a component:

  1. Mounting
  2. Updating
  3. Unmounting

 

Let’s see what they are and their associated functions one by one. 

Mounting

Mounting means putting an element into the DOM. React provides four built-in functions for it:

  1. constructor()
  2. render()
  3. getDerivedStateFromProps()
  4. componentDidMount()

 

Out of these, the render( ) method will always be called while the others are optional. 

Now, we already know about the render( ) and constructor( ) methods, so let’s see what the other two are. 

getDerivedStateFromProps( )

This method is called before the render( ) method and takes the state as an argument and returns an object with changes made to the state. 

For example, in the code below, the “name” property initially has the value Panda, but the output is Polar Bear since it is being updated to Polar Bear.

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {name: "Panda"};
    }

    static getDerivedStateFromProps(props, state) 
    {
          return {name: props.favanimal};
    }

    render() 
    {
          return (<h1>My Favorite Animal is {this.state.name}</h1>);
    }
}

ReactDOM.render(<Animal favanimal="Polar Bear"/>, document.getElementById('root’));

 

Output:


componentDidMount( )

This method is called after the render( ) method such that it changes a property in a component that is already in the DOM. This will be more clear if we see an example.

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {name: "Panda"}; 
    }

    componentDidMount() 
    {
          setTimeout(() => {this.setState({name: "Polar Bear"})}, 1000)
    }
    render() 
    {
          return (<h1>My Favorite Animal is {this.state.name}</h1>);
    }
}

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Output:

 

Here, as you can see, the value of the “name” property changes after 1000 milliseconds. 

Updating

Updating a component means a change in its state or props. The five built-in methods for updating in React are:

  1. render()
  2. getDerivedStateFromProps()
  3. shouldComponentUpdate()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

 

Like mounting, the render( ) method will always be called while the others are optional. 

We already know what the getDerivedStateFromProps( ) method does, but let’s see what the other methods do.

shouldComponentUpdate( )

This method returns a boolean value based on which a component is updated.

For example, in the code below, since the shouldComponentUpdate( ) method returns true, the “name” property changes its value on clicking the button.

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {name: "Panda"};
    }
    shouldComponentUpdate() 
    {
          return true;
    }
    
    changeName = () => 
    {
          this.setState({name: "Polar Bear"});
    }

    render() 
    {
          return (<div>
                          <h1>My Favorite Animal is {this.state.name}</h1>
                          <button type="button" onClick={this.changeName}>Change Name</button>
                    </div>);
    }
}

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Output:

 

componentDidUpdate( )

This method is called after a component is updated to trigger an updated phase. 

In the example shown below, the triggered phase can be seen by the message printed.

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {name: "Panda"};
    }

    componentDidMount() 
    {
          setTimeout(() => {this.setState({name: "Polar Bear"})}, 1000)
    }

    componentDidUpdate() 
    {
          document.getElementById("mydiv").innerHTML = "The updated favorite is "this.state.name;
    }
    render() 
    {
          return (<div>
                          <h1>My Favorite Animal is {this.state.name}</h1>
                          <div id="mydiv"></div>
                    </div>);
    }
}

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Output:



getSnapshotBeforeUpdate( )

This method shows us the value before updating. While using this method, the componentDidUpdate( ) must also be used; otherwise, we’ll get an error.

An example of this method is shown below:

class Animal extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {name: "Panda"};
    }

    componentDidMount() 
    {
          setTimeout(() => {this.setState({name: "Polar Bear"})}, 1000)
    }
    getSnapshotBeforeUpdate(prevProps, prevState) 
    {
          document.getElementById("mydiv1").innerHTML = "Before the update, the favorite was " + prevState.name;
    }

    componentDidUpdate() 
    {
          document.getElementById("mydiv2").innerHTML = "The updated favorite is "this.state.name;
    }
    render() 
    {
          return (<div>
                          <h1>My Favorite Animal is {this.state.name}</h1>
                          <div id="mydiv1"></div>
                          <div id="mydiv2"></div>
                    </div>);
    }
}

ReactDOM.render(<Animal />, document.getElementById('root'));

 

Output:


Unmounting

Mounting means adding a component to the DOM, so naturally, unmounting means removing it. There is only one method for this, and it is componentWillUnmount( ). This method is called when a component is to be removed from the DOM. 

An example of unmounting is given below.

class Container extends React.Component 
{
    constructor(props) 
    {
          super(props);
          this.state = {show: true};
    }
    delHeader = () => 
    {
          this.setState({show: false});
    }
    render() 
    {
          let myheader;
          if (this.state.show) 
          {
              myheader = <Child />;
      };
      return (<div>
                      {myheader}
                      <button type="button" onClick={this.delHeader}>Delete Header</button>
                  </div>);
      }
}

class Child extends React.Component 
{
    componentWillUnmount() 
    {
          alert("The component named Header is about to be unmounted.");
    }
    render() 
    {
          return (<h1>Hello World!</h1>);
    }
}

ReactDOM.render(<Container />, document.getElementById('root'));

 

Output:

Frequently Asked Questions

  1. What are class components in React? 
    Class components in React are the components used to track the state and lifecycle of components. For this reason, class components are also called stateful components. 
     
  2. How are class components different from functional components?
    Class components are stateful components, while functional components are stateless components. This is the main difference between them.
     
  3. Why do we need class components?
    Class components were previously used to track components’ state and lifecycle, which was impossible using functional components before React 16.8.
     
  4. Can we use functional components in place of class components in React?
    Yes, using hooks, functional components can be used in place of class components to track the state and lifecycle of components.
     
  5. Is it still essential to learn class component?
    Yes, it is still essential to learn class components since, practically, they still exist in many web pages made before hooks existed. 

Key Takeaways

In this article, we learned only about class components in React. 

I’m sure you already knew about components in React, but do not forget that there is another type of component - the functional component. If you haven’t read about it already, be sure to read about it here.

Apart from this, you can read many articles on JavaScriptReact, and various topics here or practice commonly asked coding questions on CodeStudio. There you will also find the interview experience of scholars presently working in renowned product-based companies. 

Happy Learning!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think