I cant understand what is difference between componentDidMount
and componentDidUpdate
I saw some counter app that use setState
method for increasing count value inside componentDidMount
so what if we write setState inside componentDidUpdate
?
and when should we use componentDidMount
or componentDidUpdate
?
From the docs on the component lifecycle:
componentDidMount()
: invoked immediately after a component is mounted (inserted into the DOM tree)componentDidUpdate(prevProps, prevState, snapshot)
: is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated.To make it simple, the first is called at the beginning, and the second upon every change. They are absolutely not interchangeable.
About using setState
inside componentDidUpdate
: beware! Using setState
calls componentDidUpdate
, so you might end up with an infinite loop if you call setState
at *every invocation of componentDidUpdate
.
Oh and also, here's a cool diagram to sum up the whole component lifecycle.
componentDidMount()
componentDidMount() will be rendered immediately after a component is mounted. This method will render only once and all the initialization that requires DOM nodes should go here. Setting state in this method will trigger a re-rendering.
componentDidUpdate()
componentDidUpdate() is invoked immediately every time the updating occurs. This method is not called for the initial render.
You can understand more from this below example
import React from 'react';
class Example extends React.Component{
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidMount() {
//This function will call on initial rendering.
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
render(){
return(
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
)
}
}
export default Example;
You can understand by commenting and un-commenting both life cycle methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With