The React Component Life Cycle


Learning Objectives:

After this lesson, you will be able to:

  • List the three categories of the React component life cycle.
  • Define the main methods in each life-cycle category.

The React Component Life Cycle

The life cycle comprises three main stages:

  1. When the component is being created (known as mounting).

  2. When the component is being updated.

  3. When the component is being removed from the DOM (known as unmounting).


The React Component Life Cycle

These methods are called at specific points in the rendering process. You can use them to perform actions based on what’s happening on the DOM.

  • componentDidMount(), for example, is called immediately after a component is rendered to the DOM.
  • componentWillUnmount() is called immediately before a component is removed from the DOM.

Mounting, Updating, and Unmounting

  • Initializing/mounting: For example, what happens when the component is created and inserted into the DOM? Was an initial state set? Methods are:
    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()
  • Updating: For example, did an event happen that changed the state? What happens when a component is being re-rendered? Methods are:
    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()
  • Destruction/unmounting: For example, what needs to happen when we’re done with the component? Method is:
    • componentWillUnmount()

Let’s Examine Each Category

Lifecycles
Lifecycles

The constructor() Method


The constructor() Method

React v16


The constructor() Method

Another common use of the constructor() method is to bind class methods.

For example, we could set:

In JavaScript classes, methods aren’t bound by default. So, if you pass a component’s method to a child component without binding it, its context will be bound to the child and not the parent, causing it to behave in a way other than how you intended.

Here’s an example:

React v16


The static getDerivedStateFromProps() and getSnapshotBeforeUpdate() Methods

getDerivedStateFromProps() is invoked right before calling the render() method. It should return an object to update the state or null to update nothing.

getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed (e.g., to the DOM).

Note:: These methods exists for rare use cases in which the state depends on changes in props over time (getDerivedStateFromProps()) or if you need to handle something such as scroll position before an update (getSnapshotBeforeUpdate()). It’s a best practice to explore other lifecycle methods before using these.


The componentDidMount() and componentWillUnmount() Methods

The componentDidMount method is called once, immediately after your component is rendered to the DOM. If you want to make an AJAX request when your component first renders, do so here (not in the constructor or in componentWillMount()).

In the following example, we fetch data from the server, then set the state of the component using the response:


The componentDidMount() and componentWillUnmount() Methods


The render() Method

This is the one method that every React class component must have. It is called in two parts of the component life cycle: At the beginning, when the component is being initiated/mounted, and when the component is being updated.

  • In render(), you return JSX using this.props and this.state.

The following component renders a single prop and a single state key: A car model and a speed. Once this component is mounted, its speed state will increase by 1 every second. You can try it out yourself in this CodePen.


Let’s break that down:

  • constructor()

The initial state is set to either the speed prop, or 0 if the speed prop is not passed to the component.

We bind this.incrementSpeed to the class, so that when it’s used as a callback for setTimeout, this refers to the Car class.

  • componentDidMount()

Use window.setTimeout to call this.incrementSpeed after one second (1,000 ms).

  • incrementSpeed()

this.setState(prevState => ({ speed: prevState.speed + 1 })): The speed state is set to one higher than it was previously — we add 1.

window.setTimeout(this.incrementSpeed, 1000): The incrementSpeed method is recursive — it invokes itself as the timeout callback. After one second, window.setTimeout will call this.incrementSpeed again. The speed will increase by 1, and a new timer will be set to do it again.

React v16


The shouldComponentUpdate() Method

shouldComponentUpdate() lets React know if a component’s output is not affected by the current change in state or props. The default returns true and re-renders on every state change.

If shouldComponentUpdate() returns false, then render() and componentDidUpdate() will not be invoked.


The componentDidUpdate() Method


Summary

React class components have life-cycle methods that are invoked at certain stages of their “lives” on the DOM. Some of the life-cycle methods you’ll use frequently include:

  • constructor(): Initializes state, binds methods.
  • componentDidMount(): Makes AJAX requests, gets DOM refs, binds event listeners, sets state if necessary.
  • componentWillUnmount(): Unbinds event listeners, performs other clean-up.
  • componentDidUpdate(): Updates state based on changes in components.
  • render(): Returns markup/UI.