What is the full lifecycle and methods of a component?

Question

What is the full lifecycle and methods of a component?

Answer

As covered in the Codecademy lessons, there are three main phases of a component’s lifecycle, and each phase has a set of methods that will run in sequence.

The first phase of a component’s lifecycle is the Mounting phase. This is when a component is created and inserted into the DOM. The methods that run during this phase, in order, are

componentWillMount()
render()
componentDidMount()

The next phase of a component’s lifecycle is the Updating phase. This is when a component undergoes any changes to props or state. This phase is the main part of a component’s life, and the following methods will be invoked repeatedly at each change,

componentWillReceiveProps()
shouldComponentUpdate()
render()
componentDidUpdate()

The last phase of a component’s lifecycle is Unmounting. This is when the component is removed from the DOM, and the only method run during this phase is

componentWillUnmount().

1 Like

is it not missing the constructor method first in mounting?

3 Likes

According to the React documentation componentWillMount(), which is now referred to as UNSAFE_componentWillMount() is considered legacy and you should avoid using it.

This method is invoked just before mounting occurs.

So just use constructor() and you’ll be good!

In this way the Mounting phase is like this:

4 Likes

why no componentDidUnmount in unmounting phase of component lifecycle?

2 Likes

This is just my guess Please correct me if I am wrong.
Every method of life cycle is part of a component. Ideally we should call componentDidUnmount once the component is removed from the DOM.
But Since the component is removed from the memory, we wont be able to call componentDidUnmount method.

More than anything else it completely make sense to have only one method componentWillUnmount method. Because we can use that method to clean up the space before unmounting. I don’t see a purpose of one more method componentDidUnmount other than checking if it is actually removed or not.

This thought led to an another question - what if component failed to unmount? is there a function for it?