React Life Cycle
Tags: webdev, react, javascript
Published: 2022-09-01 18:09:53

Every React web app comprises of components and these components go through some life cycle methods. 

[![react life cycle methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufbm2ojp6m38y4001p28.png)](https://www.cuelogic.com/blog/reactjs-lifecycle#:~:text=Initialisation,constructor%20of%20a%20component%20class.)


These are: 
* Initialization: First stage in React's components Life cycle. In this stage the default states and properties are intilaized.
* Mounting: Mounting is when an instance of a component is being created and inserted into the DOM.
* Updating: Updating is the stage when the state of a component is updated and component is re-rendered.
* Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.

### Initialization
```
constructor() {
        super()
        this.state = {
            show: false
        }
        console.log("Constructor ran, State has been intialized");
    }
```

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



### Mounting
React has four built-in methods that gets called, in this order, when mounting a component:

- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()

**Render** 
The render() method is the only required method in a class component.
```
    render() {
        console.log("render ran");
        return (
            <div>
                <h1>Show and Hide Counter</h1>
                <p>{this.state.text}</p>
                <button onClick={this.click}>{this.state.show ? "Hide counter" : "Show Counter"}</button>
                {this.state.show && <Counter/>}
            </div>
        )
    }
```

 The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

**componentDidMount() Function**
It runs immediately after the component is inserted into the tree(mounting).This is where we run statements that requires that the component is already placed in the DOM. 

```
    componentDidMount() {
        setTimeout(() => {
          this.setState({text: "Text was mounted first and then it was changed after 5 sec"})
        }, 5000)
        console.log("component was mounted");
      }
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0p8g219a3so9hkwsnyyr.png)

After 5 seconds

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gywjsjhrihuj60gf4kuc.png)

Mounting the Counter component:
When the show counter button is clicked  render runs again because we have changed the state.
```
    click = () => {
        if (this.state.show === false) {
            this.setState({
                show: true
            })
        }
        else{
            this.setState({
                show:false
            })
        }
    }
```
After that our counter component is rendered and mounted.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uh69ntsou32av6w5abh1.png)

### Updating 
A component is updated whenever there is a change in the component's state or props.

* componentDidUpdate
The componentDidUpdate method is called after the component is updated in the DOM.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q5su7g1mfp5k939gz28e.png)

Here when we incremented the  the component is render and updated .

* shouldComponentUpdate
In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not.

The default value is true.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eoirlz0t5qwuh395zash.png)

Even though we are clicking the increment and decrement button the component is not updating because our shouldComponentUpdate() method returns flase.
`    shouldComponentUpdate() {
        return false;
      }`

---
App.js
```
import React, { Component } from 'react'
import Counter from './counter'


export class App extends Component {
    constructor() {
        super()
        this.state = {
            show: false,
            text:"See how the text will change"
        }
        console.log("Constructor ran, State has been intialized");
    }

    // componentDidMount() {
    //     setTimeout(() => {
    //       this.setState({text: "Text was mounted first and then it was changed after 5 sec"})
    //     }, 5000)
    //     console.log("component was mounted");
    //   }
    click = () => {
        if (this.state.show === false) {
            this.setState({
                show: true
            })
        }
        else{
            this.setState({
                show:false
            })
        }
    }




    render() {
        console.log("render ran");
        return (
            <div>
                <h1>Show and Hide Counter</h1>
                <p>{this.state.text}</p>
                <button onClick={this.click}>{this.state.show ? "Hide counter" : "Show Counter"}</button>
                {this.state.show && <Counter/>}
            </div>
        )
    }
}

export default App 
```

---
counter.js

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

class Counter extends Component {
    constructor(){
        super()
        this.state={
            counter:0
        }
        
    }
    componentDidMount(){

        console.log("mounted the counter");
    }
    increment=()=>{
        this.setState(prevVal=>({
            counter:prevVal.counter-1
        }))
        console.log("button was clicked");
    }

    decrement=()=>{
        this.setState(prevVal=>({
            counter:prevVal.counter+1
        }))
        console.log("button was clicked");
    }

    componentWillUnmount(){
        console.log("unmounted");
    }
    shouldComponentUpdate() {
        return false;
      }

    componentDidUpdate(){
        console.log("component was updated");
    }

    render() {
        console.log("render ran for counter");
        return (
            <div>
                <button onClick={this.decrement}>+</button>
                <h6>{this.state.counter}</h6>
                <button onClick={this.increment}>-</button>
            </div>
        );
    }
}

export default Counter;

```








### References
* https://reactjs.org/docs/reactcomponent.html#componentdidmount
* https://www.w3schools.com/react/react_lifecycle.asp
* https://www.cuelogic.com/blog/reactjs-lifecycle