5. The React Component Lifecycle

Agata Krzywda
2 min readMar 22, 2017

--

This is the fifth part of my React tutorials. See the Intro to react.js here

In this section we will take a look at lifecycle methods in react

Each component has several “lifecycle methods” that you can use to run code at particular times in the process. Methods prefixed with will are called right before something happens, and methods prefixed with did are called right after something happens.

1. Mounting

2. Updating

3. Unmounting

The most useful are:

  • render() to display props and state as a single React element using jsx
  • constructor() where we define the initial state of the component
  • componentDidMount() which is called after the component renders for the first time. It is the best place to fetch some data from an api
  • componentWillReceiveProps() where we receive props from a parent component and we can do all the conditional operations that are related to new props being received.
  • componentDidUpdate(prevProps, prevState) here we can compare the current props/state to previous props/state, so it is the place you hook into when listening to props changes.

Here is an order which those methods are rendered

First time render (before you click on the button):

After button was clicked:

Let’s me now describe it with an example

So we have an application that has App and Counter components. In App component we store our initial state inside the constructor() method

In render() we display our Counter child component and pass the counter props.The button element has an onClick event listener that calls the incrementCounter() method and that counts how many times we click on the button

In the Counter component we can console.log() the order of all lifecycle methods:

Code at github

React is constantly watching for changes and updating your component every time it needs to be re-rendered. All of this is done via the lifecycle methods.

Here are some interesting articles about lifecycle methods:

Enjoy:)

Next tutorial Testing react components using Jest and Enzyme

--

--