Making sense of React lifecycle methods
Tags: reactnative, react, javascript, codenewbie
Published: 2020-03-03 15:33:44

What are React lifecycle methods?

I will try and give you a simple explanation to understand this perfectly. But before that, you need to know that React components do have three phases, they are:

**MOUNTING** 
**UPDATING**
**UNMOUNTING** _and_
**ERROR BOUNDARIES.**

Lifecycle methods can be describe as the series of events that happen through these react's four phases. 


_But it is not necessary a React component goes through all these four phases. The component could get mounted and unmounted  without going through the updating phase or come down to the Error boundary phase._

Let us now take a look at these phases one after the other and explain the component lifecycle method that are called in each phase.


##MOUNTING##

In the mounting stage, React has four methods that are called in this order:

_1. constructor()_
_2. getDerivedStateFromProps()_
_3. render()_
_4. componentDidMount()_



**Constructor**

This is the first lifecycle  method that is called before anything else, this is a good place to introduce and set your initial state.

You can see from the code snippet below how I initialized my state - learnLifecycle to true.

![constructor example](https://dev-to-uploads.s3.amazonaws.com/i/i3gyvbmh2se1g75yib51.png)



Wondering why you are seeing super(props) there? What does that mean again?

I don't even know myself!

Just kidding, super is what initiate the parent's constructor method and allows the component to inherit methods from its parent which is Component.


**getDerivedStateFromProps**

This is the second lifecycle that is being called after constructor, it takes in two argument which is **props** and **state**, this method either returns an object to update the state or it returns null.

This lifecycle method is called before the DOM renders, it allows a component to update its internal state in response to a change in props.

It is rarely used though and unless it is absolutely necessary, you shouldn't  use it.

Question: "When should I then use it???"

Answer: When the change in state depends on changes in props in your component.


**render**
The two lifecycle methods we've seen are optional and can only be called when you define them, Render method on the other hand is required in a React component. 
This is the method that show(renders) your JSX to the DOM.

![render example](https://dev-to-uploads.s3.amazonaws.com/i/ydnyses14x713w6qzvrb.png)



**componentDidMount**
This is my favorite lifecycle method, because here is where magic happens! 


componentDidMount is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the DOM.
This is a good place to initiate API calls, add event listeners, change state, etc.

![componentDidMount example](https://dev-to-uploads.s3.amazonaws.com/i/jqlfbofbs15woaeo7a0r.png)



And that is it for mounting phase!


##UPDATING##

Updating stage in simple terms - when there is a change in a state or props of a react component, the component is updated. But in react, instead of "updated", it is called re-render!

In the updating stage, React has five methods that are called in this order:

_1. getDerivedStateFromProps()_
_2. shouldComponentUpdate()_
_3. render()_
_4. getSnapshotBeforeUpdate()_
_5. componentDidUpdate()_


**getDerivedStateFromProps**
This has been discussed already, just note that this particular method can be called both in the mounting  phase and the updating phase.

 
**shouldComponentUpdate**
The next method called after getDerivedStateFromProps is shouldComponentUpdate. It works just like the name reads, the default value for this method is True, you can return a false boolean if you don't want the component to be updated.

![shouldComponentUpdate example](https://dev-to-uploads.s3.amazonaws.com/i/xkx681mwhrca2pj84c3l.png)


This lifecycle method is mainly use to enhance performances in our React Application.


**render**
Just like I explained before, render method **should** also be called in the updating phase.


![render example](https://dev-to-uploads.s3.amazonaws.com/i/ydnyses14x713w6qzvrb.png)

**getSnapshotBeforeUpdate and componentDidUpdate**
getSnapshotBeforeUpdate lifecycle method is called right after the render method. It is called right before the DOM is updated. 

You can either return a value or null with getSnapshotBeforeUpdate(), the value returned is passed on to componentDidUpdate().

This is also rarely use, a situation where you can use getSnapshotBeforeUpdate is when resizing the window during an async rendering (e.g. Your chat application that need to handle scroll position in a special way).

Let me give you an example from the official React documentation:

![getSnapshotBeforeUpdate example](https://dev-to-uploads.s3.amazonaws.com/i/6z9ld4phz2cxs97il76i.png)




##UNMOUNTING##

**componentWillUnmount** is the only available lifecycle method for this phase, this is the method you call when the component is about to be removed from the DOM. This is where you perform cleanups such as clearing up timers, cancelling network requests, or cleaning up any subscriptions that you created in componentDidMount().

Take for example, you created an event listener in componentDidMount(), to clear it, you go like this:

![componentWillUnmount example](https://dev-to-uploads.s3.amazonaws.com/i/80pcfben8ptfq6k6ap4e.png)



##ERROR BOUNDARIES##

We have two lifecycles under this phase, they are:

_1. static getDerivedStateFromError()_ 
_2. componentDidCatch()_


**static getDerivedStateFromError**

static getDerivedStateFromError lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state. This lifecycle method is called during rendering, so do not perform any side-effect on this method.

![getDerivedStateFromError example](https://dev-to-uploads.s3.amazonaws.com/i/ikx5yqwu4eim6pfqld2a.png)


**componentDidCatch**

Just like static getDerivedStateFromError, it is invoked after an error has been thrown by a descendant component, but this takes an extra argument which is info, to give us more information about the error.

![componentDidCatch example](https://dev-to-uploads.s3.amazonaws.com/i/yo1dicp3jtrwu7iwhho2.png)

error argument on logErrorToExternalAPI above would be the actual error message and info would be the stack trace.



And that is it, we have come to the end of this class! What a boring lecture...lol!

React lifecycle methods may not click at once, but you can keep referring to this lecture when you get confused or ask questions.