Lifecycle Method in React
When we create a react component the component goes through several stages in its lifecycle. React provides us with built-in methods that we can override at particular stages in the lifecycle. So, in this article, we will see about lifecycle method available for a class component in React JS. These methods do not exist on a functional component. With the new feature proposal of hooks, there is the use effect hook which partially relates to the lifecycle hooks but for now the focus is going to be only on the lifecycle methods in a class component. The lifecycle methods had their fair share of changes over the years. The methods we will be discussing now are for reactivation 16.4 and above. We can mainly classify the methods into four phases.
- Mounting
- Updating
- Unmounting
- Error handling.
Mounting
The Mounting lifecycle methods are called when an instance of a component is being created and inserted into the DOM. It has four methods
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()
Updating
The Updating lifecycle methods are called when a component is being re-rendering as a result of changes to either its props or state. It has five methods:
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
Unmounting
The Unmounting lifecycle methods are called when a component is being removed from the DOM. It has only one method:
- componentWillUnmount()
Error handling
The Error handling lifecycle methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component. It has two methods:
- getDerivedStateFromError()
- componentDidCatch()