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()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
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>componentDidUpdate()
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
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>componentWillUnmount()
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 Timerimport 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
import React from "react"
import ReactDOM from "react-dom"
import App from "./App"
ReactDOM.render(<App />, document.getElementById("root"))
<html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>Last updated
Was this helpful?