The componentDidUpdate()
is called after the component is updated.
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { name: "John" };
}
componentDidMount() {
setTimeout(() => {
this.setState({ name: "Billy" });
}, 1000);
}
componentDidUpdate() {
console.log("The updated value is : " + this.state.name);
}
render() {
return (
<div>
<h1>My name is {this.state.name}</h1>
</div>
);
}
}
Here the state is changed a second after the component is rendered and the component is updated after the state is changed. The componentDidUpdate()
is called after the component is updated. Here, the updated value is consoled in the componentDidUpdate()
method.