React.js Lifecycle Methods
Tags: react, javascript, webdev, tutorial
Published: 2022-05-17 19:19:49

React.js uses a declarative approach of programming. In other words, the developer only needs to declare the changes as per different states of the application. 
For this, React uses the Virtual DOM. The actual visual changes are performed using some **lifecycle methods** which provide the developer additional control over what should mount or what should update or what are the cleanups to perform before unmounting a component.

Today, we are going to discuss these lifecycle methods.


## Lifecycle methods while mounting

In this section, we will discuss the life cycle methods that are invoked when a component is initialized or mounted to the DOM.

**1. constructor():** The constructor method initializes the state and any other variables for the component. This is the first method that is called when initializing a component.


**2. static getDerivedStateFromProps():** This method is called just after the constructor initializes the component. It can update the state of the component based on the props as required.

If state is to be updated, return the updated state from this function. Otherwise, return null.

```
static getDerivedStateFromProps(props, state) {
  // some logic for syncing state and props
  // if updates --> return updated state
  // else --> return null
}
```


**3. render():** Render method is called for mounting the JSX to the DOM after the _getDerivedStateFromProps_ method.

<u>This is the only method **required** in a component.</u>

This method returns the JSX for the component that is to be mounted to the DOM. We can also return arrays and React Fragments from render method.

If _nothing_ is to be mounted we can return null from this method.

```
render() {
  if(// some condition) {
    return null; // will not render anything
  } else {
    return (//JSX or array or React.Fragment)
  }
}
```


**4. componentDidMount():** Immediately after the render method returns and the component is mounted to the DOM, this method is called.

Typical usecase for this method is to select any element from the component that was just mounted. This can then further be used to perform any subscription or make any network requests for the component just mounted to the DOM.

```
componentDidMount() {
  const x = document.getElementById('abc');
  // perform any operation on x here
  x.addEventListener() // This is also possible
  // fetch('https://google.com').then(); is also possible here
}
```


## Lifecycle methods while updating

In this section we will discuss the lifecycle methods called when updating a component which is already mounted to the DOM.

**1. static getDerivedStateFromProps():** This method runs first whenever any component is to be updated. This has been discussed earlier, so, I am skipping this here.


**2. shouldComponentUpdate()**: This method is called after the _getDerivedStateFromProps()_ method. This method returns _True_ or _False_.

This method is used to control whether this component should be updated in the DOM based on the changes to state or props. If _True_ is returned, it will proceed to update else no update will take place in the DOM.


**3. render(): ** This runs after the _shouldComponentUpdate()_ method, **if and only if** _shouldComponentUpdate()_ returns True.
This method has already been discussed above, so skipping.


**4. getSnapshotBeforeUpdate(): ** This method is invoked immediately after _render()_ method runs to update the DOM. This takes a snapshot of the DOM before the update while the visual DOM is still being updated asynchronously.

This method gets argument the previousProps and previousState which were the props and state before the update.

```
getSnapshotBeforeUpdate(prevProps, prevState) {
  return value || null; // value can be any valid javascript value
}
```

The value returned from this method is further passed to the next lifecycle method, _componentDidUpdate()_.


**5. componentDidUpdate():** This lifecycle method is called after _getSnapshotBeforeUpdate()_ method.

This method receives **previousProps**, **previousState** and **snapshot** as argument, where _snapshot_ is the value passed from the _getSnapshotBeforeUpdate()_ method.


## Lifecycle methods while unmounting

In this section, we will discuss the lifecycle method called for unmounting or removing the component from the DOM.


**1. componentWillUnmount(): ** This method is called immediately before the component is unmounted from the DOM. This function is suitable for performing any cleanup(s) before the component is removed from the DOM.

```
componentWillUnmount() {
  // remove any subscriptions or timers or unresolved network requests
  x.removeEventListener()
}
```