A day in the life of a React component
Understanding React component's lifecycle methods
Like us, humans, React components also have a life, they get born, live & update their life and eventually die. So let's dive into their life to understand them better.
What are lifecycle methods?
React components have a lifecycle: they mount when they are added to the screen, update whenever their props or states change and finally unmount when they are removed from the DOM.
We can use some methods to run some code at each stage of this lifecycle, they are called lifecycle methods
. Let's look at them one by one:
Mounting
Mounting represents the rendering of the React component in the given DOM node. Following is the order of execution for the methods, when the component is created and inserted into the real DOM:
constructor()
- We can use it to set the initial state of the component. (Caution: Avoid introducing any side-effects or subscriptions in the constructor.)getDerivedstateFromProps()
- This is called before rendering the elements in the DOM. In this method, we can set the state of the component based on the props we received.render()
- This is the only required method in the class component that we have to call. This method returns the HTML elements that will be rendered inside the DOM.componentDidMount()
- It is called right after the component is rendered inside the DOM. We can use it to make network requests to the server to get the initial data needed to serve the user.
Example :
This is a simple example to show the lifecycle of the react component in the mount phase in action. Here console.log at each method will depict the flow of execution of each method.
import React, {Component} from 'react';
import './App.css';
import Child from "./childComponent/child";
class App extends Component {
constructor(props) {
super(props);
this.state = {
randomNumber: 0,
};
console.log('[App] constructor()')
}
static getDerivedStateFromProps(props, state) {
console.log('[App] getDerivedStateFromProps')
return null;
}
componentDidMount() {
setTimeout(() => {
console.log('[App] componentDidMount')
}, 1000)
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('[App] componentDidUpdate')
}
genRandomNum = () => {
this.setState({randomNumber: Math.random()})
}
render() {
console.log('[App] render()')
return (
<div>
<div>Parent Component</div>
<button onClick={() => this.genRandomNum()}>generate a random number</button>
<Child randomNumber={this.state.randomNumber}/>
</div>);
}
}
export default App;
Updating
Updating represents the re-rendering of the React component in the given DOM node during state changes / updates. The following methods are called during the update in the same order as mentioned here:
DerivedStateFromProps()
- This method is called again when a component is being re-rendered.shouldComponentUpdate()
- This method is called before rendering the component when new props are received.render()
- To re-render the HTML inside the DOM, therender()
method gets called again.getSnapshotBeforeUpdate()
- This method is called just before the newly rendered HTML gets committed to the DOM. It stores the previous state of the component so that React has an idea of what parts of the DOM need to be updated.componentDidUpdate()
- It is called after the component gets re-rendered.
Example:
Below is the code for the child component from the previous example with all the lifecycle methods for the update phase.
import React, {Component} from 'react';
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
console.log('[Child] constructor()')
}
static getDerivedStateFromProps(props, state) {
console.log('[Child] getDerivedStateFromProps')
return null;
}
componentDidMount() {
setTimeout(() => {
console.log('[Child] componentDidMount')
}, 1000)
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
console.log('[Child] shouldComponentUpdate')
return true
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('[Child] getSnapshotBeforeUpdate')
return null
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('[Child] componentDidUpdate')
}
render() {
console.log('[Child] render()')
return (<div>Child Component {this.props.randomNumber}</div>
);
}
}
export default Child;
Unmounting
Unmounting represents the removal of the React component. The only method that gets called during unmounting of a component is:
componentWillUnmount()
- This method is called just before the component gets destroyed. Any clean up statements should be executed inside this method.
Final Output:
This concludes our peek into the life of a React component. Thank you for reading !!