Understand Life Cycles in React

Michael Tong
The Startup
Published in
2 min readAug 22, 2020
Photo by Morning Brew on Unsplash

If you have exposure to react you have probably heard of life cycles.

To understand react lifecycles, let’s understand how a web application generally behaves.

If you want to briefly summarize how a web page runs from beginning to end, here is how it’s like:

  • before rendering
  • rendering
  • listening for changes to state or props
  • finish rendering

Ultimately, when you go to facebook and see a bunch of posts, the web application actually makes an api to retrieve those posts before rendering.

Afterward, the application renders this piece of information(via render function). It listens to any changes or events that affect the state or props. When the state or the props of any components changes, the application gets re-rendered.

In react terms, they are represented in this diagram:

There are several lifecycles that affect how components are being rendered:

  • constructor
  • componentDidUpdate
  • componentDidMount
  • render
  • getDeriveStateFromProps

Let’s talk about constructor. Constructor is automatically called every time an object is created from a class. If you declare a constructor, super(props) needs to be called in order to receive props properly. Otherwise, this.props will be undefined and it can lead to all kinds of unwanted bugs.

Constructor also bind event handlers and functions during this stage.

Here is an example of how a constructor would look like:

How about componentDidUpdate? ComponentDidupdate gets called after componentDidMount and will only get called if the internal state of the component did changes, or if the component receive prop changes.

You can view the following for additional reference:

What about ComponentDidMount?

ComponentDidMount is called once, right before render is called. This is the lifecycle where you make api calls to load data remotely:

Render, as said before, is the part that throws the jsx to the browser, as seen above.

GetDeriveStateFromProps is a lifecycle where you update your internal state after changes to props. Here is an example:

That’s it to the lifecycles. Why not create an application from scratch and play around with these lifecycles?

Nothing is better than learning these concepts by applying it.

Happy coding!

--

--