# Lifecycle Methods

## `componentDidMount()`

`componentDidMount()` is invoked immediately after a **component is mounted** (inserted into the DOM tree)

{% tabs %}
{% tab title="App.js" %}

```jsx
import React from "react"
import randomcolor from "randomcolor"

class App extends React.Component {
    constructor() {
        super()
        // Initializing State
        this.state = {
            text: "Color Me",
            color: "red"
        }     
    }
    
    // Mounting the Component
    componentDidMount() {
        setTimeout(() => {
            const newColor = randomcolor()
            this.setState({color: newColor})
        }, 1000)
    }
    
    render() {
        return (
            <div>
                <h1 style={{color: this.state.color}}>{this.state.text}</h1> 
            </div>
        )
    }
}

export default App

```

{% endtab %}

{% tab title="index.js" %}

```javascript
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"

ReactDOM.render(<App />, document.getElementById("root"))

```

{% endtab %}

{% tab title="index.html" %}

```markup
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>
```

{% endtab %}
{% endtabs %}

## `componentDidUpdate()`

`componentDidUpdate()` is invoked immediately after a **component is updated** (often during event handling).

{% tabs %}
{% tab title="App.js" %}

```jsx
import React from "react"
import randomcolor from "randomcolor"

class App extends React.Component {
    constructor() {
        super()
        // Initializing State
        this.state = {
            count: 0,
            color: "red"
        }
        // Binding Class Method to App
        this.increment = this.increment.bind(this)
    }
    
    // Class Method
    increment() {
        // set a new state
        this.setState(prevState => {
            return {
                count: prevState.count + 1
            }
        })
    }
    
    // Updating the Component
    componentDidUpdate(prevProps, prevState) {
        if(prevState.count !== this.state.count) {
            const newColor = randomcolor()
            // set a new color
            this.setState({color: newColor})
        }
    }
    
    render() {
        return (
            <div>
                <h1 style={{color: this.state.color}}>{this.state.count}</h1>
                <button onClick={this.increment}>
                    Increment!
                </button>
            </div>
        )
    }
}

export default App

```

{% endtab %}

{% tab title="index.js" %}

```javascript
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"

ReactDOM.render(<App />, document.getElementById("root"))

```

{% endtab %}

{% tab title="index.html" %}

```markup
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Set `state` under a certain condition inside `componentDidUpdate` to avoid infinite loop.
{% endhint %}

## `componentWillUnmount()`

`componentWillUnmount()` is invoked immediately before a **component is unmounted and destroyed**. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in `componentDidMount()`

{% tabs %}
{% tab title="Timer.js" %}

```jsx
import React from "react"

class Timer extends React.Component{
    
    // Running (Mounting) the Timer
    componentDidMount() {
        this.intervalId = window.setInterval(() => {
            console.log("Timer is running")
        }, 2000)
    }
    
    // Cancelling (Unmounting) the Action of Timer
    componentWillUnmount() {
        window.clearInterval(this.intervalId)
    }
    
    render(){
        return(
            <p>Timer is running</p>
        )
    }
}

export default Timer
```

{% endtab %}

{% tab title="App.js" %}

```jsx
import React from "react"

import Timer from "./Timer"

class App extends React.Component {
    constructor() {
        super()
        // Initializing State
        this.state = {
            timerOn: true
        }
        this.stopTimer = this.stopTimer.bind(this)    
    }
    
    // class method
    stopTimer(){
        this.setState({
            timerOn: false
        })
    }
    
    render() {
        return (
            <div>
            {
                this.state.timerOn ? <div><button onClick={this.stopTimer}>Stop Timer</button>
                <Timer /></div> : null
            }   
            </div>
        )
    }
}

export default App

```

{% endtab %}

{% tab title="index.js" %}

```javascript
import React from "react"
import ReactDOM from "react-dom"

import App from "./App"

ReactDOM.render(<App />, document.getElementById("root"))

```

{% endtab %}

{% tab title="index.html" %}

```markup
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>
```

{% endtab %}
{% endtabs %}
