React LifeCycle Method | Day 16
Tags: javascript, webdev, beginners, programming
Published: 2022-01-24 19:03:03

### What

**Every Component in React has a lifeCycle which we can moniter or update During it’s 3 main Phases.**

So Every Component has 3 main Phase during it’s Life 

**1.) Mounting → This Means Adding the Component into the DOM.**

**2.) Updating → Updating the State or any other data of the Component.**

**3.) UnMounting → Removing the Component From the DOM.**

![React Lifecycle Method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzh85vprg95blijlk72h.png)
 

### How

**`Mounting`** 

When a Component is rendered in the DOM for the 1st Time then it is called as Mounting.

React has 3 methods that got called During Mounting.

1.) **Constructor()**

2.) **render()**

3.) **ComponentDidMount()**

Before you Move further you should know about this **the methods which are prefixed by `will` are called right `before Something happen` and the methods which are prefixed by `Did` are called right `after Something happen`.**

![Constructor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3lv8uyw1iw96v2qwbxw1.png)
 

The Constructor will called 1st and used for initialize the state and Bind the event handlers.

After that `render` will be called 

![Render](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4up4ycpt4gta6oc0youx.png)
 

After the Component is rendered React will call the **`ComponentDidMount()`.**

![React Lifecycle Method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpmja8b3usuy05k8kli0.png)
 

- **As the Component is Already Rendered if we will try to change state in the `componenetDidMount()` It will cause a `Re-rendering`.**

**Let’s have a Look to this Example** 

```jsx
import React,{Component} from "react"

class ReactLifestyle extends Component{
  constructor(props){
    super(props);
    this.state = {count:1}
    console.log('In Constructor Method')
  }
  componentDidMount(){
    console.log('IN Component Did Mount')
    this.setState({count:2})
  }
  render(){
    console.log('In Render method')
    return(
      <div>
      hi
      </div>
    )
    }
}

export default ReactLifestyle;
```

**The Output of the Code will be 👇**

![Code Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gi3v9dwsfeaurgpiblcn.png)
 

**As u can see 1st `Constructor Method` is called then `Render Method` and then `Component Did Mount`** 

**Also If we try to set state in the `ComponentDidMount` then it will cause re-rendering as u can in the output.**

[componentDidMount](https://codesandbox.io/s/componentdidmount-9jnfh?file=/src/App.js)

### Loading Data Via Ajax

```jsx
import React, { Component } from 'react';
import axios from 'axios';
import "./Zenquote.css"

class Zenquote extends Component {
    constructor(props) {
        super(props);
        this.state = {quote:"",isloading:true};  
    }
    componentDidMount() {
        //WE are adding the setTimeout so can we can get in a Condition when after rendering the Data Fetching takes time.
        setTimeout(() =>{
        axios.get("https://api.github.com/zen")
        .then((res)=>{
            console.log(res.data);
            this.setState({quote:res.data,isloading:false});
        })
        .catch((err)=>{
            console.log(err);
        })
    },1000)

    }
  render() {
    return( <div>
        {this.state.isloading? 
        (<p className="circle">
        Loading .........
        </p>)
        : (<div>
            <h3>Always Remember ....</h3>
            <p>{this.state.quote}</p>
        </div>)}
        
    </div>);
  }
}

export default Zenquote
```

- **So in the code every-time we refresh the page we got new `quote` , I use the axios to fetch the data and also , I have to  use the setTimeout to depict that sometime the data fetching take time so at that time we can add a `animated Loader`.**

### Loading data using the Async Function →

`Async/await` make promises easier to write.

**`Async` makes a function return a Promise.**

**`Await` makes a function wait for a Promise.**

```jsx
componentDidmount(){
	async GetData(){
		let res = await fetch('http://github.com.api/users');
		console.log(res);
	}
}
```

- **When we Write it will wait for the data to come then move  on to another line.**

**Example →**

```jsx
import React, { Component } from 'react';
import axios from 'axios';

class GithubUsersInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {imgUrl:"",name:"",followers:""};
    }
    async componentDidMount() {
        let user = `https://api.github.com/users/${this.props.user}`
        const res = await axios.get(user)
        console.log(res);
        this.setState({imgUrl :res.data.avatar_url,name:res.data.name,followers:res.data.followers})
    }
  render() {
    return <div>
        <h2>Github User Name : {this.state.name}</h2>
        <img src={this.state.imgUrl} alt="image"/>
        <p>Followers : {this.state.followers}</p>
    </div>;
  }
}

export default GithubUsersInfo
```

- This takes user name as a props.
- **This will gives us the Github User Data.**

### ComponentDidUpdate →

![Code Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/elool626o97jecldzk7a.png)
 

Updating can be done by changing the the State , Props (Changed Form the Parent Side) , or any other External Data.

Like **`forceUpdate` is used to update the things which are not in the state and often they are external Data  so to change that we can use the `forcedata()`.**

![React Lifecycle method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/784lqn3msu1nk51k8fth.png)
 

When we update Something Re-rendering Happen after then **`ComponentDidUpdate()` called.**

**So we can use the `ComponentDidUpdate()` to save all your data into the database which has been changed .**

![componentDidUpdate](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yw3u34hszoy3mkl40lbp.png)
 

### Example →

```jsx
import React, { Component } from 'react';
import axios from 'axios';
import "./Zenquote.css"

class Zenquote extends Component {
    constructor(props) {
        console.log("In Constructor")
        
        super(props);
        this.state = {quote:"",isloading:true};  
    }
    componentDidMount() {
        console.log("In Component Did Mount")
        setTimeout(() =>{
        axios.get("https://api.github.com/zen")
        .then((res)=>{
            this.setState({quote:res.data,isloading:false});
        })
        .catch((err)=>{
            console.log(err);
        })
    },1000)

    }
    componentDidUpdate(){
        console.log("In Component Did Update")
    }
  render() {
      console.log("Rendering .....")
    return( <div>
        {this.state.isloading? 
        (<p className="circle">
        Loading .........
        </p>)
        : (<div>
            <h3>Always Remember ....</h3>
            <p>{this.state.quote}</p>
        </div>)}
        
    </div>);
  }
}

export default Zenquote
```

The Output of the Below Code is :

![Code Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orwj8kdcny9xm9a81gv6.png)
 

**1st the Constructor is called , then rendering happened and then ComponentDidMount got called and in the ComponentDidMount we change the State so this causes the Re-rendering and when we change the state after Re-rendering the `ComponentDidUpdate` Got called.**

Whenever u update something the `ComponentDidUpdate` got called after Re-rendering. So we can use the Component Did Mount to save the data to the Database.

Also In the Component Did Update we can access the **Previous State and the Previous Props so U can use this to compare the State or props with the previous ones.**

**To use the Previous state and prop u should write like this.**

```jsx
componentDidUpdate(prevProps,prevState){
	// Inside this u can use the previous props & the state 
	console.log(prevProps);
	console.log(this.props);
}
```

- **Remember the 1st argument will be the previous props and the 2nd argument will be previous state.**

### ComponentWillUnmount()

**This will be called when we are removing something from the DOM** 

![ComponentWillUnmount](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a380old8vot85zh7kyht.png)
 

```jsx
componenetWillUnmount(){
	console.log('In Component Will Unmount')
	//It will be called before the removal of the Component.
}
```

Happy Coding 🙂