Component Life-Cycle: React comes with many lifecycle methods. Each of them has its own purpose and acts during different phases of a component’s lifetime, like mounting, updating, unmounting, or during error handling.
Every React component goes through a cycle from its inception and mounted onto the Document Object Model (more commonly known as the DOM) to the point of its being unmounted and destroyed from DOM. This is called the component lifecycle. React class components use these methods to control the cycle while React functional components use hooks to manage the lifecycle.
The lifecycle of the component is divided into four phases. They are:
1. Initial Phase
2. Mounting Phase
3. Updating Phase
4. Unmounting Phase
Each phase contains some lifecycle methods that are specific to the particular phase. Let us discuss each of these phases one by one.
Initial Phase
This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class. The initial phase only occurs once and consists of the following methods.
getDefaultProps()
It is used to specify the default value of this.props. It is invoked before the creation of the component or any props from the parent are passed into it.
getInitialState()
It is used to specify the default value of this.state. It is invoked before the creation of the component.
Mounting Phase
Mounting is the stage of rendering the JSX returned by the render method itself. The instance of a component is created and inserted into the DOM. These are the lifecycle methods available for this phase:-
componentWillMount()
As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time.
componentDidMount()
This is invoked immediately after a component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
render()
The render() method is the only method that the component is required to have. It will always be called and its job is to mount the component to the DOM.
Updating Phase
This second phase represents times when a component needs to update due to a change in its props or state. These changes can occur within the component or through the backend. These changes will trigger the render function again. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of the following methods.
componentWillRecieveProps()
This is the first method that will be called when the component gets an update. The use case of this method is to update the state based on prop changes when props aren’t sufficient to be directly used.
shouldComponentUpdate()
It is invoked when a component decides any changes/updation to the DOM. It allows you to control the component’s behavior of updating itself. If this method returns true, the component will update. Otherwise, the component will skip the updating.
componentWillUpdate()
As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props.
render()
It is invoked to examine this.props and this.state and return one of the following types: React elements, Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.
componentDidUpdate()
This method is always called right after a component render and has updated the DOM. It receives two values as arguments,
prevProps — Props of the component before the update
prevState — State of the component before the update
Unmounting Phase
There is only unmounting method in React 16. the unmounting phase is where the component is removed from the DOM. This is very useful to destroy a component from the DOM. It can be used to perform cleanups such as removing event listeners, invalidating timers or intervals, etc. This marks the end of a component’s lifecycle.
componentWillUnmount()
his method is invoked immediately before a component is destroyed and unmounted permanently. It performs any necessary cleanup-related tasks such as invalidating timers, and event listeners, canceling network requests or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.
Example
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props)
{
super(props);
this.state = { hello : "World!" };
}
componentWillMount()
{
console.log("componentWillMount()");
}
componentDidMount()
{
console.log("componentDidMount()");
}
changeState()
{
this.setState({ hello : "Techie!" });
}
render()
{
return (
<div>
<h1>techiebundle.com, Hello{ this.state.hello }</h1>
<h2>
<a onClick={this.changeState.bind(this)}>Press Here!</a>
</h2>
</div>);
}
shouldComponentUpdate(nextProps, nextState)
{
console.log("shouldComponentUpdate()");
return true;
}
componentWillUpdate()
{
console.log("componentWillUpdate()");
}
componentDidUpdate()
{
console.log("componentDidUpdate()");
}
}
ReactDOM.render(
<Test />,
document.getElementById('root'));
Overview
React follows a proper path of calling all lifecycle methods, which are called in different phases of a component’s lifetime. Starting from before the component is created, then when the component is mounted, updated, or unmounted, and finally during error handling.
All of them have their own roles but some are used more often than others. The only required method in the whole lifecycle is the render() method. We can say that those lifecycle methods are the ones that provide React with its real power.
Read more
React create-react app
State vs Props in React
ReactJS Constructor() Method
Component API in ReactJS