React lifecycle
Created on: Sep 13, 2024
There are three phases in a react component lifecycle.
- Mounting
- Updating
- Unmounting
Let's understand this concept with below example.
import React from "react"; class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; console.log("Constructor"); } static getDerivedStateFromProps(props, state) { console.log("getDerivedStateFromProps"); return null; // No state update required } componentDidMount() { console.log("componentDidMount"); } shouldComponentUpdate(nextProps, nextState) { console.log("shouldComponentUpdate"); return true; } getSnapshotBeforeUpdate(prevProps, prevState) { console.log("getSnapshotBeforeUpdate"); return null; } componentDidUpdate(prevProps, prevState, snapshot) { console.log("componentDidUpdate"); } componentWillUnmount() { console.log("componentWillUnmount"); } render() { console.log("Render"); return ( <div> <h1>Count: {this.state.count}</h1> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Increment </button> </div> ); } } export default Counter;
You can checkout whole code from my github repo ,install dependency and run the code. Check the console while initial rendering for mounting phase. click on button and check console for update phase.
1. Mounting
In this phase, component is mounted on the DOM and rendered for the first time on the webpage. These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
getDerivedStateFromProps enables a component to update its internal state as the result of changes in props.
The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes.
2. Updating
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
Important Points:
- shouldComponentUpdate is used to check if a component’s output is not affected by the current change in state or props.
- getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to the DOM. It enables component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to componentDidUpdate().
Unmounting
This method is called when a component is being removed from the DOM:
- componentWillUnmount(): It is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount().