Component’s lifecycle methods in ReactJS -part 1

Kavini Welarathne
2 min readMar 12, 2020

--

Today, I wanted to share some of the basic stuff about Component life-cycle methods. Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence.

Okay, enough of the talk, let’s get to work!

“You can think of React lifecycle methods as the series of events that happen from the birth of a React component to its death.”

Here goes the lifecycle diagram…

The lifecycle can be divided into three phases

1. Mounting

2. Updating

3. Unmounting.

The methods that are called within these intervals are called “lifecycle hooks”.

During Mounting, the following methods are called in order

  • constructor → getDerivedStateFromProps →render →componentDidMount.

During Updating, the following methods are called in order

  • getDerivedStateFromProps →shouldComponentUpdate, →render, →getSnapshotBeforeUpdate →componentDidUpdate

During Unmounting,

  • componentWillUnmount

Now let’s try to understand these methods one by one…

constructor

Once initialization has completed, an instance of the component is created and mounted onto the DOM.

This is a special function that will get called whenever a new object is created.This is also the only place where you are expected to change/set the state by directly overwriting the this.state fields. Do not call setState. Always call super(props) to bind this.props.

getDerivedStateFromProps

The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM.

The example below starts with the favorite color being “red”, but the getDerivedStateFromProps() method updates the favorite color based on the favored attribute:

render

Render is the only required method and it returns the element. It takes this.props and this.state and render them on DOM.

Called every time state or props are getting changed.

componentDidMount

componentDidMount is called just after the render method, It always Updates UI with new data.

setState() in this will call render method again and so your component will have data rendering without any hassle.

Ugh…give me a break. I explaining other methods in another blog.

If you enjoyed this piece, I’d love it if you hit the clap button 👏 so others might stumble upon it. You can find my own code on Github.

Thanks for reading!

See you soon ❤️

--

--

Kavini Welarathne
Kavini Welarathne

Written by Kavini Welarathne

Software Engineer | Researcher |

No responses yet