In ReactJS, every component creation process involves various lifecycle methods. These lifecycle methods are termed as component's lifecycle. These lifecycle methods are not very complicated and called at various points during a component's life. The lifecycle of the component is divided into four phases. They are:
Each phase contains some lifecycle methods that are specific to the particular phase. Let us discuss each of these phases one by one.
It is the birth phase of the lifecycle of a ReactJS component. Here, the component starts its journey on a way to the DOM. In this phase, a component contains the default Props and initial State. These default properties are done in the constructor of a component. The initial phase only occurs once and consists of the following methods.
In this phase, the instance of a component is created and inserted into the DOM. It consists of the following methods.
It is the next phase of the lifecycle of a react component. Here, we get new Props and change State. This phase also allows to handle user interaction and provide communication with the components hierarchy. The main aim of this phase is to ensure that the component is displaying the latest version of itself. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of the following methods.
It is the final phase of the react component lifecycle. It is called when a component instance is destroyed and unmounted from the DOM. This phase contains only one method and is given below.
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {hello: "rookienerd"};
this.changeState = this.changeState.bind(this)
}
render() {
return (
ReactJS component's Lifecycle
Hello {this.state.hello}
);
}
componentWillMount() {
console.log('Component Will MOUNT!')
}
componentDidMount() {
console.log('Component Did MOUNT!')
}
changeState(){
this.setState({hello:"All!!- Its a great reactjs tutorial."});
}
componentWillReceiveProps(newProps) {
console.log('Component Will Recieve Props!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component Will UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component Did UPDATE!')
}
componentWillUnmount() {
console.log('Component Will UNMOUNT!')
}
}
export default App;Output:
When you click on the Click Here Button, you get the updated result which is shown in the below screen.