What is componentDidUpdate in Reactjs With Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

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

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →