In React, each component has several "lifecycle methods" that you can override to run code at particular times in the process. These methods are used for various purposes like setting up subscriptions, fetching data from APIs, handling animations, and cleaning up before the component is unmounted.
The lifecycle methods can be broadly categorized into three parts: Mounting, Updating, and Unmounting.
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
constructor()static getDerivedStateFromProps()render()componentDidMount()An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()shouldComponentUpdate()render()getSnapshotBeforeUpdate()componentDidUpdate()This method is called when a component is being removed from the DOM:
componentWillUnmount()
Here's a simple example of a class component with lifecycle methods:
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
color: 'blue'
};
}
componentDidMount() {
console.log('Component mounted');
}
componentDidUpdate() {
console.log('Component updated');
}
componentWillUnmount() {
console.log('Component will unmount');
}
render() {
return (
<div>
{this.state.color}
</div>
);
}
}
export default Example;