Lifecycle Methods

What’s a Lifecycle Method?

Lifecycle methods are methods that get called at certain moments in a component’s life.

You can write a lifecycle method that gets called right before a component renders for the first time.

You can write a lifecycle method that gets called right after a component renders, every time except for the first time.

You can attach lifecycle methods to a lot of different moments in a component’s life. This has powerful implications!

Mounting Lifecycle Methods

There are three categories of lifecycle methods: mounting, updating, and unmounting

A component “mounts” when it renders for the first time. This is when mounting lifecycle methods get called.

There are three mounting lifecycle methods:

  • componentWillMount
  • render
  • componentDidMount

When a component mounts, it automatically calls these three methods, in order.

 

componentWillMount

The first mounting lifecycle method is called componentWillMount.

When a component renders for the first time, componentWillMount gets called right before render.

Look at Example.js

import React from ‘react’;
import ReactDOM from ‘react-dom’;

export class Example extends React.Component {
  componentWillMount() {
    alert(‘component is about to mount!’);
  }

  render() {
    return <h1>Hello world</h1>;
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById(‘app’)
);

setTimeout(() => {
  ReactDOM.render(
    <Example />,
    document.getElementById(‘app’)
  );
}, 2000);

 

and follow these steps:

  1. On lines 14-17, <Example /> is rendered for the first time. <Example />‘s mounting period begins.
  2. <Example /> calls the first mounting lifecycle method, componentWillMount.
  3. componentWillMount executes, and an alert appears on the screen. (lines 5-7)
  4. After componentWillMount has finished, <Example /> calls the second mounting lifecycle method: render.
  5. <h1>Hello world</h1> appears on the screen (lines 9-11)
  6. Two seconds later, <Example /> renders again (lines 20-22).componentWillMount does NOT get called, because mounting lifecycle events only execute the first time that a component renders.

You can call this.setState from within componentWillMount!

Look at Example2.js 

import React from ‘react’;
import ReactDOM from ‘react-dom’;

export class Example2 extends React.Component {
  constructor(props) {
    super(props);

    this.state = { text: };
  }

  componentWillMount() {
    this.setState({ text: ‘Hello world’ });
  }

  render() {
    return <h1>{this.state.text}</h1>;
  }
}

ReactDOM.render(
  <Example2 />,
  document.getElementById(‘app’)
);

 

for an example of this.setState inside of componentWillMount. See if you can follow how <Example2 /> would render <h1>Hello world</h1>.

Render

render is a lifecycle method! We won’t go over render here – we’ve already talked about it plenty. However, you should understand how render fits into the mounting period. Whenever a component mounts, componentWillMount is called first, followed by render, followed by componentDidMount.

render belongs to two categories: mounting lifecycle methods, and updating lifecycle methods. We’ll cover updating lifecycle methods in the next lesson. But first, there’s one final mounting lifecycle method!

componentDidMount

The final mounting lifecycle method is called componentDidMount.

When a component renders for the first time, componentDidMount gets called right after the HTML from render has finished loading.

If your React app uses AJAX to fetch initial data from an API, then componentDidMount is the place to make that AJAX call. More generally, componentDidMount is a good place to connect a React app to external applications, such as web APIs or JavaScript frameworks.componentDidMount is also the place to set timers using setTimeout or setInterval.

If that sounds vague, don’t worry. You’ll put lifecycle methods into practice in this course’s final project, and then more in the next course! Not to mention in the real world…

 

import React from ‘react’;
import ReactDOM from ‘react-dom’;

export class Flashy extends React.Component {
  componentWillMount() {
    alert(‘AND NOW, FOR THE FIRST TIME EVER…  FLASHY!!!!’);
  }
 
  componentDidMount() {
    alert(‘YOU JUST WITNESSED THE DEBUT OF…  FLASHY!!!!!!!’);
  }

  render() {
    alert(‘Flashy is rendering!’);
   
    return (
      <h1 style={{ color: this.props.color }}>
        OOH LA LA LOOK AT ME I AM THE FLASHIEST
      </h1>
    );
  }
}

ReactDOM.render(
  <Flashy color=’red’ />,
  document.getElementById(‘app’)
);

setTimeout(() => {
  ReactDOM.render(
    <Flashy color=’green’ />,
    document.getElementById(‘app’)
  );
}, 2000);

 

Updating Lifecycle Methods

There are two categories that we haven’t yet discussed: updating and unmounting lifecycle methods. This lesson covers both.

What is updating?

The first time that a component instance renders, it does not update. A component updates every time that it renders, starting with the second render.

There are five updating lifecycle methods:

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

Whenever a component instance updates, it automatically calls all five of these methods, in order.

componentWillReceiveProps

The first updating lifecycle method is called componentWillReceiveProps.

When a component instance updates, componentWillReceiveProps gets called before the rendering begins.

As one might expect, componentWillReceiveProps only gets called if the component will receive props:

// componentWillReceiveProps will get called here:
ReactDOM.render(
  <Example prop=“myVal” />,
  document.getElementById(‘app’)
);

// componentWillReceiveProps will NOT get called here:
ReactDOM.render(
  <Example />,
  document.getElementById(‘app’)
);

 

Look in the code below for an example of componentWillReceiveProps. Read it through and try to figure out how it works.

import React from ‘react’;

export class Example extends React.Component {
  componentWillReceiveProps(nextProps) {
    alert(“Check out the new props.text that “
    + “I’m about to get:  “ + nextProps.text);
  }

  render() {
    return <h1>{this.props.text}</h1>;
  }
}


// The first render won’t trigger
// componentWillReceiveProps:
ReactDOM.render(
<Example text=”Hello world” />,
document.getElementById(‘app’)
);

// After the first render,
// subsequent renders will trigger
// componentWillReceiveProps:
setTimeout(() => {
ReactDOM.render(
<Example text=”Hello world” />,
document.getElementById(‘app’)
);
}, 1000);

 

componentWillReceiveProps automatically gets passed one argument: an object called nextProps. nextProps is a preview of the upcoming props object that the component is about to receive.

On line 6, nextProps.text will evaluate to “Hello world”.

shouldComponentUpdate

The second updating lifecycle method is called shouldComponentUpdate.

When a component updates, shouldComponentUpdate gets called after componentWillReceiveProps, but still before the rendering begins.

Look at Example.js:

// Example  

import React from ‘react’;

export class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = { subtext: ‘Put me in an <h2> please.’ };
  }

  shouldComponentUpdate(nextProps, nextState) {
    if ((this.props.text == nextProps.text) &&
      (this.state.subtext == nextState.subtext)) {
      alert(“Props and state haven’t changed, so I’m not gonna update!”);
      return false;
    } else {
      alert(“Okay fine I will update.”)
      return true;
    }
  }

  render() {
    return (
      <div>
        <h1>{this.props.text}</h1>
        <h2>{this.state.subtext}</h2>
      </div>
    );
  }
}

 

 Read it through and try to figure out how shouldComponentUpdate works.

shouldComponentUpdate should return either true or false.

If shouldComponentUpdate returns true, then nothing noticeable happens. But if shouldComponentUpdate returns false, then the component will not update! None of the remaining lifecycle methods for that updating period will be called, including render.

The best way to use shouldComponentUpdate is to have it return false only under certain conditions. If those conditions are met, then your component will not update.

shouldComponentUpdate automatically receives two arguments: nextProps and nextState. It’s typical to compare nextProps and nextState to the current this.props and this.state, and use the results to decide what to do. See how Example.js does this on lines 10-19.

 

componentWillUpdate

The third updating lifecycle method is componentWillUpdate.

componentWillUpdate gets called in between shouldComponentUpdate and render.

componentWillUpdate receives two arguments: nextProps and nextState. Read Example to see it in action.

You cannot call this.setState from the body of componentWillUpdate! Which begs the question, why would you use it?

The main purpose of componentWillUpdate is to interact with things outside of the React architecture. If you need to do non-React setup before a component renders, such as checking the window size or interacting with an API, then componentWillUpdate is a good place to do that.

If that sounds abstract, that’s okay! All of the lifecycle methods might feel a bit theoretical, until you’ve used them in real-life scenarios.

 

import React from ‘react’;

export class Example extends React.Component {
  componentWillUpdate(nextProps, nextState) {
    alert(‘Component is about to update!  Any second now!’);
  }

  render() {
    return <h1>Hello world</h1>;
  }
}

 

componentDidUpdate

The last updating lifecycle method is componentDidUpdate.

When a component instance updates, componentDidUpdate gets called after any rendered HTML has finished loading.

Look at Example for an example of componentDidUpdate.

componentDidUpdate automatically gets passed two arguments: prevProps and prevState. prevProps and prevState are references to the component’s props and state before the current updating period began. You can compare them to the current props and state.

componentDidUpdate is usually used for interacting with things outside of the React environment, like the browser or APIs. It’s similar to componentWillUpdate in that way, except that it gets called after render instead of before.

 

import React from ‘react’;

export class Example extends React.component {
  componentDidUpdate(prevProps, prevState) {
    alert(‘Component is done rendering!’);
  }

  render() {
    return <h1>Hello world</h1>;
  }
}

componentWillUnmount

A component’s unmounting period occurs when the component is removed from the DOM. This could happen if the DOM is rerendered without the component, or if the user navigates to a different website or closes their web browser.

componentWillUnmount is the only unmounting lifecycle method!

componentWillUnmount gets called right before a component is removed from the DOM. If a component initiates any methods that require cleanup, then componentWillUnmount is where you should put that cleanup.

You can see an example in Example.js, as usual.

 

import React from ‘react’;

export class Example extends React.Component {
  componentWillUnmount() {
    alert(‘Goodbye world’);
  }

  render() {
    return <h1>Hello world</h1>;
  }
}

Review

Congratulations on making it to the end of our Introductory React courses! By this point, you have acquired all of the tools that you need to program in React.