A React component's lifecycle consists of a series of methods that are invoked at various stages. The lifecycle of a component can be controlled and manipulated using these methods.
Furthermore, there are a few other lifecycle methods available, such as static getDerivedStateFromError() and componentDidCatch().
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Count updated');
}
}
componentWillUnmount() {
console.log('Component will unmount');
}
incrementCount() {
this.setState(prevState => ({
count: prevState.count + 1,
}));
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}
export default MyComponent;
Using this example, we have a MyComponent class component that maintains a count. Here are the methods used in the lifecycle:
Constructors are called when components are first created. A 0 is set as the initial count when the state is initialized.
As soon as a component is mounted (i.e., inserted into the DOM), this method is invoked. A console message is logged to indicate that we have mounted the component in this example.
Whenever a component updates and re-renders, this method is called. In addition to the previous props and state, it receives the new props and state as arguments. Whenever there is a difference between the previous count and the current count, we log a message.
When the component is unmounted and destroyed, this method is invoked. You can use it to perform any cleanup operations you need. This example logs a message to the console indicating that the components will be unmounted.