Lifecycle Methods

Each component has a lifecycle. The 3 phases are - Mounting, Updating, & Unmounting. Lifecycle methods are used to trigger certain actions when a component undergoes a specific part of its lifecycle.

componentDidMount()

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

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

componentDidUpdate()

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

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

Set state under a certain condition inside componentDidUpdate to avoid infinite loop.

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()

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

Last updated

Was this helpful?