
React Components Lifecycle
In React, every component creation process involves multiple lifecycle methods. The lifecycle of a component is divided into three main phases:
- Mount
- Update
- Unmount
Mount
In this phase, the component gets inserted into the DOM. While Mounting a component, these methods get called, in the mentioned sequence:
constructor()
getDerivedStateFromProps()
render()
componentDidMount()
The render()
is the only required method. All other methods are optional, and are called if defined.
constructor()
Method
The constructor()
method is called as soon as the component is initiated. It is the place where states
can be defined and initialized. Here's an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
this.state = {
value : 1
}
}
render(){
return (
<h3>Our Class Component Value : {this.state.value} </h3>
)
}
}
ReactDOM.render(<FirstComponent />, document.getElementById('root'));
getDerivedStateFromProps()
Method
This method is invoked right before calling the render
method. It should return an object to update the state, or return NULL to update nothing.
This method is used very rarely as it is used where the state depends on changes in props over time. Here's an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
this.state = {
value : 1
}
}
static getDerivedStateFromProps(props, state) {
return {value: props.val };
}
render(){
return (
<h3>Our Class Component Value : {this.state.value} </h3>
)
}
}
ReactDOM.render(<FirstComponent val="1" />, document.getElementById('root'));
render()
render()
method is the only essential method, and is used to render HTML. Here's an example:
class FirstComponent extends React.Component {
render(){
return (
<h3>This is the render method </h3>
<p>The only essential Method</p>
)
}
}
ReactDOM.render(<FirstComponent/>, document.getElementById('root'));
componentDidMount()
This method is called once the component is rendered. It can contain statements and methods that need to be executed after the component is placed in the DOM.
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
//Will get invoked once the component is rendered
componentDidMount(){
this.setState({
value: 10
})
}
render(){
return (
<h3>This is the updated value {this.state.value} </h3>
)
}
}
ReactDOM.render(<FirstComponent/>, document.getElementById('root'));
Update
This is the next phase of the lifecycle of a React Component. A component gets updated as soon as the component's state or props changes.
When a component gets updated, there are 5 methods in React that get called. The methods are listed below in the order they get called:
getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
getDerivedStateFromProps()
This is the first method that gets called when a component gets updated. State can be set or modified in this method. Here's an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
//Will get invoked once the component is rendered
static getDerivedStateFromProps(props, state) {
return {value: props.val };
}
clickHandler(){
this.setState({
value: 5
})
}
render(){
return (
<h3>This is the updated value {this.state.value} </h3>
<button onClick={this.clickHandler}>Button</button>
)
}
}
ReactDOM.render(<FirstComponent val="10"/>, document.getElementById('root'));
shouldComponentUpdate()
This method returns a boolean value. The default value is true
. It continues with the normal behavior when the value is true. In case of false
, the component doesn't get updated. Here's an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
shouldComponentUpdate() {
return false; //In case of false, the component will not update
}
clickHandler(){
this.setState({
value: 5
})
}
render(){
return (
<h3>This is the updated value {this.state.value} </h3>
<button onClick={this.clickHandler}>Button</button>
)
}
}
ReactDOM.render(<FirstComponent val="10"/>, document.getElementById('root'));
render()
The render()
method gets called every time the compoent is updated.
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate()
method is invoked right before the most recently rendered HTML output is inserted into the DOM. It enables us to capture any data related to the DOM before it is potentially changed.
Let's have a look at an example. In this example, we'll be using the previous and the current values to demonstrate.
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
componentDidMount() {
// Changing the state after 1 sec
setTimeout(() => {
this.setState({ value: 2 });
}, 1000);
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Displaying the previous value of the state
document.getElementById('previous-val').innerHTML =
'Previous Value: ' + prevState.value;
}
componentDidUpdate() {
// Displaying the current value of the state
document.getElementById('new-val').innerHTML =
'Current Value: ' + this.state.value;
}
render(){
return (
<div id="previous-val"></div>
<div id="new-val"></div>
)
}
}
ReactDOM.render(<FirstComponent val="10"/>, document.getElementById('root'));
So in the above example, when the component has been mounted, the timer changes the state. So after 1 second, the state is updated.
Due to this, the update phase is triggered. As we have defined the getSnapshotBeforeUpdate()
method, it will get executed, and will write a message to our first div.
After this, the componentDidUpdate()
method will get executed and will write the message to the second div.
componentDidUpdate()
componentDidUpdate()
method is called when the component is updated on the DOM. Let's have a look at an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
componentDidMount() {
// Changing the state after 1 sec
setTimeout(() => {
this.setState({ value: 2 });
}, 1000);
}
componentDidUpdate() {
// Displaying the current value of the state
document.getElementById('original-val').innerHTML =
'Current Value: ' + this.state.value;
}
render(){
return (
<div id="original-val"></div>
)
}
}
ReactDOM.render(<FirstComponent val="10"/>, document.getElementById('root'));
In the above example, when the component has been mounted, the timer updates the state.
Due to this, update phase is triggered. Since we have defined componentDidUpdate()
method on this component, it will execute this method, and text will be displayed within the div.
Unmount
Unmounting is the next phase in which the component is removed from the DOM. There's one built-in method for the unmounting phase in React:
componentWillUnmount()
componentWillUnmount()
This method is triggered when a component is unmounted from the DOM. Let's check an example:
class FirstComponent extends React.Component {
constructor(props){
super(props)
//State Declared
this.state = {
value : 1
}
}
componentWillUnmount() {
alert('Component will unmount now!');
}
render(){
return (
<h3>This is a heading</h3>
)
}
}
In the above example, an alert box will appear as soon as the component is unmounted from the DOM.