In the words of the mesmerizing Lana Del Rey, everything is ‘born to die.’ From processes to people, every aspect of the physical reality has a definitive beginning and a distinctive end. They are born, evolve, grow old and then die. (Read: become obsolete. We don’t want to be too morbid.) So, just as everything else follows a lifecycle, the same applies to ReactJS components.
Once a specific component is created, it is then mounted on the DOM, where developers enhance its functionalities by upgrading it. Then once the component is obsolete, it is unmounted from the DOM. This is the React JS component lifecycle.
The ReactJS component lifecycle consists of certain specific methods deployed to each phase of the component’s lifecycle. ReactJS can call the required method in alignment with the phase of the component. This gives the ReactJS development/maintenance team a stronger and more pervasive control over the target component. With the help of the lifecycle methods of ReactJS, developers can manipulate the state of the component. So what are these lifecycle methods? Well, that’s the question we are here to address. Read on as we talk about the four major Lifecycle methods of ReactJS-
Lifecycle Methods In ReactJS, the component lifecycle can be segregated into four major parts-
- Initialization
- Mounting
- Updating
- Unmounting
Now let’s get down to a discussion of the different lifecycle methods that apply to each of these phases-
1. Initialization
In this phase, the component begins its journey by building a state and its required props. This process is carried out by the constructor method. Here is an e.g. of initialization with a constructor.
class Initialize extends React.Component {
constructor(props)
{
// Calling the constructor of
// Parent Class React.Component
super(props);
// initialization process
this.state = {
date : new Date(),
clickedStatus: false
};
}
2. Mounting
It is very clear from its name that the React component is mounted on the DOM in this phase. This means that it is created in the DOM, or a pre-fab component is inserted into the DOM.
The Mounting phase is launched post the Initialization phase. In the Mounting phase, the component is rendered in runtime for the very first time. Here is a list of the methods that can be deployed to this phase-
- componentWillMount()
This method is activated just before the component is mounted onto the DOM and before the render method is called for. After this method, the component is mounted. Ensure that you do not create any API calls or make any data change using this.setstate in this method. This is because this method is called before the render method, and no changes can be made to the DOM as the component hasn’t yet been mounted. This means that the state cannot be updated with an API response.
- componentDidMount()
This method is called once the component is properly mounted on the DOM. Similar to componentWillMount, this method is called for just once in the entire component lifecycle. The render method is called (to access the DOM) just before the execution of this method. Developers can make API calls and update the state with an API response now that the component is rendered on the DOM. Here is an example of this mounting method:
Must Read: Most Recommended ReactJS Tools to Optimize Web App Performance
It is called once in a lifecycle. Before executing this method, the render method is called (i.e., we can access the DOM). We can make API calls and update the state with the API response.
class LifeCycle extends React.Component {
componentWillMount() {
console.log(‘Component will mount!’)
}
componentDidMount() {
console.log(‘Component did mount!’)
this.getList();
}
getList=()=>{
/*** method to make api call***
}
render() {
return (
<div>
<h3>Hello mounting methods!</h3>
</div>
);
}
}
3. Updating
Updating is the third phase of the component lifecycle. Post the Mounting phase, where the component now exists on the DOM and has been rendered, and the next phase is updating/upgrading the component to support increased functionalities. The state of the component changes, and a re-rendering occurs.
In the Updating phase, the component’s data (its props and states) are updated to respond to user events like a click or a type input. Each input from the user causes the component to re-render. The methods available for this phase are-
- shouldComponentUpdate()
With this method, developers can get a perspective on whether or not the component requires an update. The default response is of this method is true (yes). IF the developer wishes to re-render the component for any reason, then the shouldComponentUpdate method works perfectly.
Consider this example- If a developer wants to re-render a component because of a prop change, the shouldComponentUpdate method is the most effective option as not only does it receive and compute arguments like nextProps and nextState but also helps the developer decide whether or not to re-render the component by comparing it to the current prop value.
- componentWillUpdate()
Like all the other methods mentioned, this method’s function lies in its name. This method is called right before an instance of re-rendering. It is also called once after the ‘shouldComponentUpdate’ method.
This method is perfect if the developer wishes to carry out a certain calculation before the component is re-rendered but after the state and prop are defined. Similar to the ‘shouldComponentUpdate’ method, this method also computes arguments like nextProps and nextState.
- ComponentDidUpdate()
This method is called immediately after the component is re-rendered. This method is executed once the updated (new) component is updated on the DOM. This method I capable of computing arguments like prevProps and prevState.
Here is an example of the method in action:
class LifeCycle extends React.Component {
constructor(props)
{
super(props);
this.state = {
date : new Date(),
clickedStatus: false,
list:[]
};
}
componentWillMount() {
console.log(‘Component will mount!’)
}
componentDidMount() {
console.log(‘Component did mount!’)
this.getList();
}
getList=()=>{
/*** method to make api call***
fetch(‘https://api.mydomain.com’)
.then(response => response.json())
.then(data => this.setState({ list:data }));
}
shouldComponentUpdate(nextProps, nextState){
return this.state.list!==nextState.list
}
componentWillUpdate(nextProps, nextState) {
console.log(‘Component will update!’);
}
componentDidUpdate(prevProps, prevState) {
console.log(‘Component did update!’)
}
render() {
return (
<div>
<h3>Hello Mounting Lifecycle Methods!</h3>
</div>
);
}
}
4. Unmounting
Unmounting is the final phase of the component lifecycle. True to its name, the component is unmounted from the DOM and is retired in this phase. The method for this phase is-
- component will unmount()
This method is called just when the developer desires to unmount the component in question. Before the component is removed from the DOM, ‘component will unmount’ executes. This method is the end of the component’s lifecycle.
In Summation- This can get Complex
So there you have it. A clear idea of the different phases of the component lifecycles and the best methods to execute within each phase. But ReactJS development can get tricky if you don’t have the right team working on your development initiative. Here is where the need for an experienced partner comes into play. Let your partner handle coding while you handle your core business. We trust that this article has proven informative. Until next time, happy developing.