What is componentDidUpdate in Reactjs With Example

04-Apr-2023

.

Admin

In this blog i would like to explain about componentDidUpdate in react js. componentDidUpdate is a method of component life cycle. this method call after any props or stats are updated. if you need to update anythings after state update then this is good place.

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the following example. network request may not be necessary if the props or state have 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;

I hope it can help you...

#React.js