State and Lifecycle

Kabir Singh
Last Updated: May 13, 2022

Introduction

The terms State and lifecycle sound pretty interesting don’t they?

But what do they actually mean? What can we make out of reading state and lifecycle?

Let’s read it out!

As we have always studied, React is a library that helps us create front-end views easily. It has a huge treasure of libraries that work along with it. Not only this, it can easily come in handy to enhance our existing applications.

So this article will take us around the State and Lifecycle of react components and how we can easily change and update them internally and their internal State.

Now let's have a very quick look at the State that is used in react components.

What is State?

Whenever we wish to make our react component classes dynamic, the best approach is to use State. 

This basically enables our components to keep track of the change in information that takes place in between the renders.

We can sum this up by saying that the state component can be defined as an object that holds information that has possibilities of changing over the lifetime of a component.

Also, there are read-only components that are present in react called as props. So let’s have a look at the difference between state and prop.

State

Props

Here changes can be asynchronousThese are read-only
State is mutableThese are immutable
These can’t be accessed by the child componentProps can be easily accessed by child component
Stateless components can’t have a stateThe stateless components can have props
These can’t make components reusableThese can make components reusable

 

But how can we use this State? Let's see!

Using State

Whenever we wish to use a state, it is a compulsion that the State of a component should always exist, and to do this, we set an initial state. And this can be possible by a very easy method.

We can directly define our state in the constructor of our components class.

Let’s see how?

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {datenew Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, Ninjas </h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

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

 

OUTPUT

 


That's it? Defining a state was that simple? But how do we update this State now? Let's have a quick look at that too!

Updating State

There is a very simple rule that we follow whenever we work with react and its state component, and that is that we can never explicitly update a state.

This means that we will use an observable object for the specific State that will allow our component to behave accordingly.

Let’s see the code to the same:

this.state.attribute = "changed-value";

 

In the given example, if we observe we are using a handleClick() method that updates the correct value of the Counter as soon as it is updated on the UI.

 

import React from "react";

import ReactDOM from "react-dom";

 

class Counter extends React.Component {

 constructor(props) {

   super(props);

 

   this.state{

     counter: 0

   };

 

   this.handleClickthis.handleClick.bind(this);

 }

 

 handleClick() {

   this.state.counterthis.state.counter1;

 

   console.log("counter", this.state.counter);

 }

 

 render() {

   const { counter } = this.state;

 

   return (

     <div>

       <button onClick={this.handleClick}>Increment counter for Ninjas</button>

       <div>Ninja's Counter value is {counter} </div>

     </div>

   );

 }

}

 

const rootElement = document.getElementById("root");

ReactDOM.render(<Counter />, rootElement);

 

 


OUTPUT

 

But once we use this, we will directly come across a render error! And this will lead to our State not being able to detect changes.

And to avoid such kind of a situation, we tend to use a built-in function called setState()

This function directly takes an object as an input containing the set values, which we tend to update.

This method would first update our State and then call the render()  method and re-renders the page.

Now let’s quickly look at the code for the same:

this.setState({attribute"changed-value"});

 

But what if we want to set multiple amounts of states? How can we do that? Let's see in the next section!

Setting the Multiple States

We can easily set multiple states in just one setState() by making use of the asynchronous abilities to react. It can be used in real-life projects where we wish to count a specific thing like the number of likes on a youtube video.

We can implement this using the ES6 arrow function and the code would turn out to be as follows:

this.setState((prevState, props) => ({

 total: prevState.count + props.diff

}));

 

We can also implement the same thing i.e taking our prevstate component and our prop by putting them into a regular function and the code would look something like this:

this.setState(function(prevState, props){

 return {total: prevState.count + props.diff};

});

 

Now, Since we are completely clear about the State and how we can define a state and also setting up multiple states, let's not waste time and go to the next section that introduces us to the next half of this article, i.e., Lifecycle!

Lifecycle

So in general English language lifecycle can be classified as the journey from birth to death, including the growing period in between. Similarly, our react components have a journey, i.e., they are created at first (also called mounting) and then they go through some growth (also called as updating) and then they die (termed as unmounted), and this results in the complete Lifecycle of a react component.

The entire lifecycle of a component can be classified into several phases, and each phase has a different lifecycle method. Now let's look at the lifecycle methods of these mentioned phases.

The Lifecycle Methods

There are four parts of the Lifecycle of a component in react, which are as follows:

  1. Initialization
  2. Mounting 
  3. Updating 
  4. Unmounting 

 

Let’s have a deeper look into each of these now:

Initialization

Usually taking place inside the constructor method, this phase involves the setting of the State and props.

The code somewhat looks like this:

class Initialize extends React.Component {

  constructor(props){

    // Here we call the constructor of its parents

    super(props);

    // Here takes place the initialization process

    this.state = {

      time: new Date(),

      selectedStatus: false

    };

  }

}

 

Moving to the next phase now we will have a look at the process of mounting:

Mounting

This is a successive method after the initialization, and this basically gives birth to our react component. This states that this is the first time our react component loads as it is created and inserted into the DOM. there are two methods that are available to us during this phase, and they are:

componentWillMount()

This method is basically called before the mounting takes place on the DOM or exactly when the render method is called and then the component gets mounted.

componentDidMount()

Once the component is mounted on the DOM we call this method. Just like componentWillMount(), this can also be called only once in a lifecycle. And before it is executed, the render method is called. We make API calls and update the state with the API response.

Let's see how our code looks while we implement both of these methods in our mounting phase.

class NinjaLifeCycle extends React.Component {
  componentWillMount() {
      console.log('Component will mount!')
  }


  componentDidMount() {
      console.log('Component did mount!')
      this.getData();
  }
  getData=()=>{

  }
render() {
      return (
        <div>
            <h1>Let's mount some methods!</h1>
        </div>
      );
  }
}

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


OUTPUT

 


Updating

After creating our component in the mounting phase, we move to the next phase, which is the update phase. This is the actual phase where the component changes the State, and the re-rendering of the component happens too!

So the State and the props of the component that can accumulatively be called its data generally update in response to the user actions that involve typing, clicking, etc., and this results in re-rendering of the component. We have three methods that we can use for the same, and they are:

shouldComponentUpdate()

We use This method to determine whether the component should be updated or not. By default, it returns true. If at some point, we want to re-render the component on a condition, then the shouldComponentUpdate() method would be the correct choice.

componentWillUpdate()

This method is called before the re-rendering our component takes place. It is called once after shouldComponentUpdate().If we want to perform a calculation prior to the re-rendering process of the component & after updating the state and prop, then we would use this method. Like shouldComponentUpdate(), this also receives arguments like nextProps and nextState.

componentdidUpdate()

We call this method after the re-rendering process of our component takes place. After the updated component gets completely updated on the DOM, the componentDidUpdate() method is executed. This method receives arguments like prevProps and prevState.

class LifeCycle extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      timenew Date(),
      selectedStatusfalse,
      list:[]
    };
  }
  componentWillMount() {
    console.log('Component will mount!')
  }
  componentDidMount() {
    console.log('Component did mount!')
    this.getList();
  }
  getList=()=> {
  
    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ list:data }));
  }
  shouldComponentUpdate(nextProps, nextState) {
    return this.state.list!==nextState.list
  }
  componentWillUpdate(nextProps, nextState) {
    console.log('Component will update!');
  }
  componentDidUpdate(prevProps, prevState) {
    console.log('Component did update!')
  }
render() {
  return (
    <div>
      <h1>Mounting methods in action!</h1>
    </div>
  );
}
}


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


OUTPUT

 

That was easy! But now we wish to end this Lifecycle too! And this process or phase is termed as unmounting, and this is the last phase of our Lifecycle. Let's have a look at the last phase now.

Unmounting

This is the last phase where we unmount our component from the DOM. This is the method that we can use here:

componentWillUnmount()

This method takes place before we get to unmounting, i.e., before the removal of our component from the DOM. This method directly ends the component lifecycle.

class ComponentNinja extends React.Component {
 
  // Defining the componentWillUnmount method
  componentWillUnmount() {
    alert('The component is going to be unmounted');
  }
 
  render() {
    return <h1>Hello from Coding Ninjas!</h1>;
  }
}
 
class App extends React.Component {
  state = { display: true };
  delete = () => {
    this.setState({ display: false });
  };
 
  render() {
    let comp;
    if (this.state.display) {
      comp = <ComponentNinja />;
    }
    return (
      <div>
        {comp}
        <button onClick={this.delete}>
          Delete the component
        </button>
      </div>
    );
  }
}
 

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

 

OUTPUT




 

 If we press the delete the component button, it will delete the component and would give an alert on the screen about the same. 






 

So finally, we are done with the entire study of State and the Lifecycle of react components. Now let's quickly see some frequently asked questions.

Frequently Asked Questions

1. What is the lifecycle method?
So in normal English language, lifecycle can be classified as the journey from birth to death, including the growing period in between. Similarly, our react components have a journey, i.e., they are created at first (also called mounting) and then they go through some growth (also called updating), and then they die (termed as unmounted), and this results in the complete Lifecycle of a react component.


2. What is the State?
Whenever we wish to make our react component classes dynamic in nature, then the best approach is to use State.


3. How many parts does a component lifecycle have?
There are four parts of the Lifecycle of a component in react, which are as follows:

  • Initialization
  • Mounting
  • Updating
  • Unmounting

 

4. What is mounting?

This is a successive method after the initialization, and this basically gives birth to our react component. This states that this is the first time our react component loads as it is created and inserted into the DOM. 

Key Takeaways

So we have had a long journey reading this article and understanding state and lifecycle. But let’s just take two minutes and summarize what we read in this article.

This article takes you through a very readily used component of react called State and also talks about how you can use it in your react code. Not only this, but we also have a look at the Lifecycle of components and the various lifecycle methods too.

We hope the entire concept of state and lifecycle was made clear in this article!

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

Happy Learning Ninjas!

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think