The React lifecycle is something that all components in React will follow, depending on if your component is being created, updated or destroyed, a series of React lifecycle methods will be executed in a particular order. There is a long list of potential lifecycle methods we could talk about and some are used more than others, but to prevent this getting too long we’re going to focus on some of the most commonly used methods. 

Chances are you will get asked something about the React lifecycle methods in your interview, now it’s unlikely that the interviewer is going to expect you to know every lifecycle method, but they may ask about some of the more common ones. To help you prepare below are some potential questions you might get asked and some info to help you answer them.

What is the React lifecycle?

When a component is created, updated or destroyed in React it will follow the React lifecycle. The React lifecycle is implemented every time a component changes and involves executing a series of built in lifecycle methods. These methods are executed automatically and can be leveraged to perform actions, improve the efficiency of your components and reduce the amount of code you need to write.

Examples of the types of actions that can be performed inside of lifecycle methods include performing an AJAX request to retrieve some data we want to use in our app, using lifecycle methods also saves time as we don’t have to create additional functions in our app when we want to perform these actions. 

There are alot of different lifecycle methods but generally the React lifecycle will consist of the component being created (mounted), updated and destroyed (unmounted).

For example, when a component is created (mounted) the following lifecycle methods will be called:

  1. constructor()
  2. render()
  3. componentDidMount()

When a component is updated the following lifecycle methods will be called:

  1. shouldComponentUpdate()
  2. componentWillUpdate()
  3. render()
  4. componentDidUpdate()

Finally when a component is destroyed (unmounted) the below lifecycle method is called:

  1. componentWillUnmount()

We now know some of the common React lifecycles that components will go through in React, but what are these methods doing inside of the React lifecycle? Too keep this a reasonable length we aren’t going to cover every lifecycle method, but we will talk about some of the most commonly used ones, keep reading to learn more about what these methods do in the React lifecycle.

What is the constructor() lifecycle method?

The constructor() method is the first method called in the React lifecycle and is primarily used to set the initial state of the component and pass in any props. constructor(props) initiates the constructor method and passes in props to the component, the initial state of the component is set here by calling this.state={ }. As a rule its advised to not call setState() inside this lifecycle method as its primarily used to set the initial state.

super(props) is placed inside the components constructor() method and calls the constructor() method of the parent. The reason we do this is because it allows us to access the functions of a parent and allows us to access this.props inside the constructor() method (note this only applies to the constructor() method).

In this method you can also bind any helper functions you have created by including this.myFunction = this.myFunction.bind(this), this is important because if you create a function and don’t bind it in the constructor() method you won’t be able to access it, however, if you are creating these functions using arrow functions you won’t have to bind them.

Example:

constructor(props){

    super(props);        

    this.state = {

             books: [ ]

         };

    this.myFunction = this.myFunction.bind(this);

  }

What is the render() lifecycle method?

The render method is one of the most commonly used methods in the React lifecycle and is where you create the visual aspects of your component on screen. In this method JSX (syntactic sugar that looks like HTML but is actually JavaScript) is used to define what will be shown in the User Interface (UI) and display it to the user. Each time the component needs to re-render e.g when calling setState() the render() method will be called and the UI will update (if applicable). Some conditional rendering might be performed here to display different UI elements to the user but generally logic is not executed in this lifecycle method.

Example:

render(

<div>Hello</div>

)

What is the componentDidMount() lifecycle method?

ComponentDidMount() is a lifecycle method that is executed after a component in React has mounted to the DOM and render() has been called. One of the most common things you can do during the componentDidMount() lifecycle method is to perform AJAX requests. The reason for this is because if you require some data from an AJAX request for your component it may mount before the request has returned data, as a result this could cause issues with your app. Calling setState() and updating the state of your component in this lifecycle method is advised as the component will finish mounting before updating the state and automatically re-rendering the component. 

This method is executed only once when the component is initially mounted, if you need to make recurring AJAX requests consider ComponentDidUpdate() as this is executed once per update (but not on the initial mounting/rendering).

Example:

componentDidMount(){

     const request = axios.get(‘/’);

    this.setState({

firstState: request

    });

  }

What is the shouldComponentUpdate() lifecycle method?

The shouldComponentUpdate() method is a lifecycle method that allows your component to exit the update lifecycle if it is not necessary to execute a new render. The main purpose of this is for optimization, by preventing unnecessary rerenders (e.g as a result of being triggered by a parent component) it will improve the efficiency of your components and application. It does this by comparing the state and props of the component with the next state and props it will receive, if they are different it returns True (rerenders), if they are the same it returns False (does not rerender). For example in the below example if the colors on the state or props are not the same then rerender, otherwise don’t rerender.

 

Example:

 shouldComponentUpdate(nextProps, nextState) {

    if (this.props.color !== nextProps.color) {

      return true;

    }

    if (this.state.count !== nextState.count) {

      return true;

    }

    return false;

  }

What is the componentDidUpdate() lifecycle method?

The componentDidUpdate() lifecycle method is similar to the componentDidMount() method in that it can be used to perform an AJAX request and perform actions after the component has finished rendering. The difference is however that componentDidUpdate() will not run on the initial mounting, it is executed whenever the component updates and is executed multiple times unlike componentDidMount() which is only executed once.

Example:

componentDidUpdatet(){

     const request = axios.get(‘/’);

    this.setState({

firstState: request

    });

  }

Conclusion

When a component is created, updated and destroyed in React it will follow the React lifecycle. The React lifecycle contains a series of React lifecycle methods that are executed in a particular order depending on what the component is doing. The constructor() method is primarily used to set the initial state of the component and map props, the render() method is used to render elements on screen using JSX, the componentDidMount() method is used to execute actions e.g AJAX requests after the component has mounted, and the componentDidUpdate() method is used to perform actions after the component has updated.

 

Related Questions

What is getDerivedStateFromProps() in React?

getDerivedStateFromProps()  is a new lifecycle method in React that is acting as a replacement for componentWillRecieveProps() the difference is setState() is not called inside this method and instead returns a plain object, this object can then be used in componentDidUpdate() to update the state of the component.

Can i get a diagram of the React lifecycle?

During the React lifecycle alot of different lifecycle methods are being executed and it can be hard to track, click here to download a simple diagram for the React lifecycle displaying what happens during the mounting, updating and unmounting of a component.