React Lifecycle methods-Simplified

What is a component Lifecycle?

When a react app is built it is built using smaller components. These components are created (mounted on the DOM), grow by updating, and then die (unmounted on DOM). This is what we know as a component lifecycle.

For learning basic of React you can refer my post:

Every component in React goes through a lifecycle of events. Let us think of it as the cycle of human life.

  • Mounting — A component is born
  • Update — It grows
  • Unmount — Our poor component dies.
React Life-cycle

Let’s see different methods present in different stages of the lifecycle. We will cover them later in this blog.

Mounting

Mounting is the phase in which our component mounts on the DOM (i.e., is created and inserted into the DOM).

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Note:

There are also some legacy methods that need to be avoided now. we will not cover those methods in this blog

  • UNSAFE_componentWillMount()

Updating

A component gets updated when the props or state changes.

These methods are called in the following order when a component is being re-rendered:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

Note:

Legacy methods that should be avoided.

  • UNSAFE_componentWillUpdate()
  • UNSAFE_componentWillReceiveProps()

Unmounting

In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.

This method is called when a component is being removed from the DOM:

  • componentWillUnmount()

Let's dive into some commonly used methods

Constructor(props)

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

Typically, in React constructors are only used for two purposes:

  • Initializing local state by assigning an object to this.state.
  • Binding event handler methods to an instance.
class VideoManager extends React.Component {     constructor(props){ 
super(props); // calling parent class constructor
this.state = { // initialization process
totalVideoCount: 0
};}
}

render()

this is the only required method in a class component.

The render() method handles the rendering of components to the UI, that happens during the mounting and updating of components

class VideoManager extends Component{     render(){
return <div>VideoManager Page!</div>
}
}

Render() method should be kept as a pure function that means you should not change state or interact with the browser in the render method. Interaction with browser and changing states should be done in other methods such as componentDidMount().

componentDidMount()

When our component gets mounted and is ready, that's when componentDidMount() comes in action. We can make API calls in this function and update our states.

class LifeCycle extends React.Component {       constructor(props){
super(props);
this.state = {
totalVideoCount: 0
};
}
componentDidMount = async () => console.log('___Component did mount____')
let count=await this.getVideoCount();
this.setState({totalVideoCount:count})
}getVideoCount(){
//api call that return total video count
}
render() {
return (
<div>
<h3>Video Count {this.state.totalVideoCount}</h3>
</div>
);
}
}

componentDidUpdate()

componentDidUpdate(prevProps, prevState, snapshot)

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

componentDidUpdate() can be used to perform tasks based on the change of previous state or props but make sure to do this on a condition check to avoid an infinite loop.

componentWillUnmount()

componentWillUnmount() is called before a component is unmounted and killed. Whatever resources that were acquired in componentDidMount() can be released now.

Rarely Used Lifecycle Methods

React lifecycle methods

shouldComponentUpdate()

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate() is invoked before rendering when new props or states are being received. Defaults to true. This method is not called for the initial render or when forceUpdate() is used.

static getDerivedStateFromProps()

getDerivedStateFromProps() is called before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

Note that this method is fired on every render, regardless of the cause. This is in contrast to UNSAFE_componentWillReceiveProps, which only fires when the parent causes a re-render and not as a result of a local setState.

getSnapshotBeforeUpdate()

getSnapshotBeforeUpdate(prevProps, prevState)

React recently introduced this method which is a safer alternative to the previous lifecycle method componentWillUpdate().

It enables your component to capture some information from the DOM before it is changed. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate()

Conclusion:

In this blog, we tried to cover the react lifecycle methods that are the latest and most frequently used. We also pointed out some legacy methods that are not used now. Try to follow the most frequently used methods for avoiding unnecessary rendering and application optimization.

Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store