Dilip Kumar
CodinGurukul
Published in
9 min readOct 4, 2019

--

In this post, we will dive deep into new lifecycle components methods of React v16.3+.

React V 16.3.0 has introduced significant changes in lifecycle methods with the aim to improve user experience in context to which some of the lifecycle methods used earlier have been deprecated.

Methods that have been deprecated are

  1. componentWillMount().
  2. componentWillUpdate().
  3. componentWillReceiveProps().

These methods are still there in react but it is recommended to avoid the use of them.They exists with different name in react now like

componenWillMount() to UNSAFE_componentWillMount().

componentWillUpdate() to UNSAFE_componentWillUpdate().

componentWillReceiveProps() to UNSAFE_componentWillReceiveProps().

If you are not aware of what this term actually means don't worry we will be covering things in this post.

What is lifecycle methods?

In this world, everything goes through a set of events.

Like humans growth moves from childhood to adulthood and progresses to elderhood similarly in react we have, mounting, updating and unmounting..

If you are not aware of this term don’t worry we will be discussing it. Having a knowledge of phases that a component undergo gives us more control over component.

Let's see what those terms actually mean

So if I ask you to build a component that renders this “hey i am here to help you”.I am sure you will go ahead and write something like this.

class Example extends React.Component {
render(){
return <h1 className="displayText">hey i am here to help</h1>
}
}

When this component is rendered and viewed, you may end with a view like this

The component had gone through a couple of phases before getting here. These phases are generally referred to as component lifecycle.

So now you have understood what component lifecycle is .. let's move towards exploring this lifecycle

The first phase that a component undergo is called Mounting it is the same as bringing a newborn baby to this world.

All the component before mounting reside in Virtual DOM that is inside our CPU memory on mounting all the components are loaded to the browser DOM.

It doesn’t end here. A React component “grows”. i.e, the component goes through the second phase i.e updating phase.

For react components, without updates, the component will remain as they were when they were created in the DOM world.

A number of components that you write get updated with requirements via state or props.

The final phase a component goes through is the Unmounting phase.

At this stage, the component dies i.e it is removed from its world -the DOM.

wait there is one more phase i.e Error Handling Phase, same as humans visit to doctor. Some time our code contains error or bug, in that case, it goes through Error Handling Phase

Now you understood the four important life cycles of the react component.

  1. Mounting- same as bringing a newborn baby to the world.
  2. Updation-A react component undergoes changes.
  3. UnMounting-The final phase
  4. Error Handling- when there is bug or code does not work.

Cool, that all for the phases, now its time to dig deep into these phases there are couple of methods that react provide us during each phases, these phases are popularly known as React life cycle methods.

Understanding the methods associated with each phase

Knowing the phases the component goes through is one part of the equation. The other part is understanding the methods react makes available at each phase.

Let’s have a look at the methods available on all 4 phases — mounting, updating, unmounting and error handling.

Let’s begin by having a look at the methods unique to the Mounting phase.

The mounting lifecycle methods

The mounting phase refers to the phase from when a component is created and inserted to the DOM.

The following methods are called in order.

1. constructor()

This is the very first method called as the component is “brought to life”.

The constructor method is called before the component is mounted to the DOM.

Usually, you’d initialize state and bind event handlers' methods within the constructor method.

const Example extends React.Component {
constructor(props) {
super(props)
this.state = {
goals: 0
}
this.handleGoals = this.handleGoals.bind(this)
}
}

What’s important to note is that this is the first method invoked — before the component is mounted to the DOM.

Also, the constructor is NOT where to introduce any side-effects or subscriptions such as event handlers.

2. static getDerivedStateFromProps()

Before explaining how this lifecycle method works, let me show you how the method is used.

The basic structure looks like this:

const Exammple extends React.Component {
...

static getDerivedStateFromProps(props,state) {
//do stuff here
}
}

these methods take in props and state. And you can either return an object like this

... 

static getDerivedStateFromProps(props, state) {
return {
goals: 2// update state with this
}
}

...

or you can return null to make no updates like this

... 

static getDerivedStateFromProps(props, state) {
return null;
}

...

I know what you’re thinking. Why exactly is this lifecycle method important? Well, it is one of the rarely used lifecycle methods, but it comes in handy in certain scenarios.

Remember, this method is called (or invoked) before the component is rendered to the DOM on initial mount.

Let's understand this with an example.

Consider a simple component that renders the number of goals scored by a hockey team.

class App extends Component {
state = {
goals:2
}

render() {
return (
<div className="App">
<p>
You've scored {this.state.goals} goals.
</p>
</div>
);
}

Note that the text reads, your scored total of 2 goals — where 2 is the number of goals in the state object.

Just an as an example, if you put in the static getDerivedStateFromProps the method as shown below, what number of goals will be rendered?

class App extends Component {
state = {
goals: 2
}

static getDerivedStateFromProps(props, state) {
return {
goals:5
}
}
render(){
return (
<div className="App">
<p>
You've scored {this.state.goals} goals.
</p>

</div>
);
}
}

Right now, we have the static getDerivedStateFromProps component lifecycle method in there. If you remember from the previous explanation, this method is called before the component is mounted to the DOM. By returning an object, we update the state of the component before it is even rendered.

And here’s what we get:

With the 5 coming from updating state within the static getDerivedStateFromProps method.

Well, this example is contrived, and not really the way you’d use the static getDerivedStateFromProps method. I just wanted to make sure you understood the basics first.

With this lifecycle method, just because you can update the state doesn’t mean you should go ahead and do this. There are specific use cases for the static getDerivedStateFromProps method, or you’ll be solving a problem with the wrong tool.

So when should you use the static getDerivedStateFromProps lifecycle method?

The method name getDerivedStateFromProps comprises five different words, “Get Derived State From Props”.

Essentially, this method allows a component to update its internal state in response to a change in props.

You could read that again if you need it to sink in.

3. Render

After the static getDerivedStateFromProps the method is called, the next lifecycle method in line is the render method:

class Example extends React.Component {
// render is the only required method for a class component
render() {
return <h1> Lets see Rendering </h1>
}
}

If you want to render elements to the DOM, the render method is where you write this (as shown above) i.e returning some JSX.

4. componentDidMount()

After render is called, the component is mounted to the DOM, and the componentDidMount method is invoked.

This function is invoked immediately after the component is mounted to the DOM.

Sometimes you need to grab a DOM node from the component tree immediately after it’s mounted. This is the right component lifecycle method to do this.

If you also want to make network requests as soon as the component is mounted to the DOM, this is a perfect place to do so as well:

componentDidMount() {
this.fetchListOfPosts() // where fetchListOfTweets initiates a netowrk request to fetch a certain list of tweets.
}

With this, we come to the end of the Mounting phase. Let’s have a look at the next phase the component goes through — the updating phase.

The updating lifecycle methods

Whenever a change is made to the state or props of a react component, the component is re-rendered. In simple terms, the component is updated. This is the updating phase of the component lifecycle.

So what lifecycle methods are invoked when the component is to be updated?

1. static getDerivedStateFromProps()

Firstly, the static getDerivedStateFromProps method is also invoked. That’s the first method to be invoked. I already explained this method in the mounting phase, so I’ll skip it.

What’s important to note is that this method is invoked in both the mounting and updating phases. The same method.

2. shouldComponentUpdate()

As soon as the static getDerivedStateFromProps method is called, the shouldComponentUpdate method is called next.

By default, or in most cases, you’ll want a component to re-render when state or props change. However, you do have control over this behavior.

Within this lifecycle method, you can return a boolean — true or false and control whether the component gets re-rendered or not i.e upon a change in state or props.

This lifecycle method is mostly used for performance optimization measures. However, this is a very common use case, so you could use the built-in PureComponent when you don’t want a component to re-render if the stateand props don’t change.

3. render()

After the shouldComponentUpdate method is called, render is called immediately afterward – depending on the returned value from shouldComponentUpdate which defaults to true .

Right after the render method is called, the getSnapshotBeforeUpdatelifecycle method is called next.

This one is a little tricky.

Chances are you may not always reach out for this lifecycle method, but it may come in handy in certain special cases. Specifically when you need to grab some information from the DOM (and potentially change it) just after an update is made.

Here’s the important thing. The value queried from the DOM getSnapshotBeforeUpdate will refer to the value just before the DOM is updated. Even though the render method was previously called.

An analogy that may help has to do with how you use version control systems such as git.

A basic example is that you write code, and stage your changes before pushing to the repo.

In this case, assume the render function was called to stage your changes before actually pushing to the DOM. So, before the actual DOM update, information retrieved from getSnapshotBeforeUpdate refers to those before the actual visual DOM update.

Actual updates to the DOM may be asynchronous, but the getSnapshotBeforeUpdate lifecycle method will always be called immediately before the DOM is updated.

4. componentDidUpdate()

This lifecycle method is invoked after the getSnapshotBeforeUpdate is invoked. As with the getSnapshotBeforeUpdate method it receives the previous props and state as arguments:

componentDidUpdate(prevProps, prevState) {

}

Whatever value is returned from the getSnapshotBeforeUpdate lifecycle method is passed as the third argument to the componentDidUpdate method.

Let’s call the returned value from getSnapshotBeforeUpdate, snapshot, and here’s what we get thereafter

componentDidUpdate(prevProps, prevState, snapshot) {

}

The unmounting lifecycle method

The following method is invoked during the component unmounting phase.

componentWillUnmount()

The componentWillUnmount lifecycle method is invoked immediately before a component is unmounted and destroyed. This is the ideal place to perform any necessary cleanup such as clearing up timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() as shown below:

componentDidMount() {
addEventListener()
}

// e.g remove event listener
componentWillUnmount() {
removeEventListener()
}

We will be discussing the methods associated with the error handling phase in the later part of this post. I hope you have understood the rest methods associated with mounting, updating and unmounting phases.

‘what are some things that I did well?’ and ‘what are some things I could have done differently or better?’”

Feel free to express your feedback and you can clap for this article if this post deserves that.

--

--

Dilip Kumar
CodinGurukul

Frontend Developer @Invizai. Loves to build web design and product. Always available to contribute