Home reactjs What is componentDidUpdate in Reactjs With Example

What is componentDidUpdate in Reactjs With Example

by Shahriar Sagor

Today now in this blog i would like to share with you about componentDidUpdate in react js. We know that componentDidUpdate is a method of component life cycle. So this method is call after any props or any stats are updated. So if we need to update anythings after state update then this is a good place.

Here we can call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition as like in the following example. So network will request can not be necessary if the props or state can not changed.

componentDidUpdate() Example

/src/User.js file

import React from 'react'

class User extends React.Component{

    constructor(){
        console.warn('constructor call')
        super();
        this.state = {
            active:null,
            name:null,
            email:null
        }
    }

    componentDidUpdate(){
        console.warn('componentDidUpdate call')
        if(this.state.name == null && this.state.email == null){
            this.setState({
                name:"nicesnippets",
                email:"nicesnippets@gmail.com"
            });
        }
    }

    render(){
        console.warn('render call')
        return(
            <div>
                <h1>User Name : {this.state.name}</h1>
                <h1>User Email : {this.state.email}</h1>
                <button onClick={()=>{this.setState({active:'yes'})}}>Get User Info</button>
            </div>
        )  
    }
}

export default User;

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

close

You may also like