What is componentDidUpdate in Reactjs With Example
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:"[email protected]"
});
}
}
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;
- How to Reactive Forms with Validation in Angular 18?
- Reactjs Props Example With Function and Class Components
- React Color Picker Example With Change Event
- How to Hide and Show Multiple Div in React ?
- React js File Upload Example With Axios
- How to Resize, Crop, Compress Images Before Uploading In ReactJS?
- How to Send Data From React to Node JS Express?
- Reactjs String Replace Example