React Lifecycle

Irena Popova 👩🏻‍💻 - Jun 22 '20 - - Dev Community

One of my favorite parts of learning React so far has been understanding the React component lifecycle. The component lifecycle goes through the following phase

  • Mounting
  • Updating
  • Unmounting

Mounting

The component rendered to the DOM for the first time. This is called mounting. These methods are called in the following order when an instance of a component is being created and inserted into the DOM.

constructor()
static getDerivedStateFromProps() rarely case use
render()
componentDidMount()

Updating

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered

static getDerivedStateFromProps() rarely case use
shouldComponentUpdate() rarely case use
render()
getSnapshotBeforeUpdate() rarely case use
componentDidUpdate()

Unmounting

When component removed from DOM. This is called unmounting. Below method is called in this phase.

componentWillUnmount()

Lifecycle Methods

constructor()
The constructor for a React component is called before it is mounted. The constructor call only once in whole lifecycle. You and set initial value for this component.

Constructors are only used for two purposes 1. Initializing local state by assigning an object to this.state 2. Binding event handler methods to an instance.

constructor(props){
    super(props);
    this.state = {qty: this.props.qty}
    this.clickHandling = this.clickHandling.bind(this);
}
Enter fullscreen mode Exit fullscreen mode

From the lifecycle methods in React.js then render() is the most used method. If React component has to display any data then it uses JSX. React uses JSX for templating instead of regular JavaScript.

Actually render() is the most used method for any React powered component which returns a JSX with backend data. It is seen as a normal function but render() function has to return something whether it is null. When the component file is called it calls the render() method by default because that component needs to display the HTML markup or we can say JSX syntax.

This method is the only required method in a class component. The render() function should be pure, meaning that it does not modify component state, which means it returns the same output each time it’s invoked.

render(){
    return(
      <div>
        <h2>Cart Items ({this.state.qty})</h2>
      </div>
    )
  }
Enter fullscreen mode Exit fullscreen mode

It is good to keep in mind that we must return something, if there is no JSX for the return then null would be perfect, but must return something. In that scenario, you can do something like this.

import { Component } from 'react';


class App extends Component {
  render() {
    return null;
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Another thing to keep in mind is that setState() cannot be defined inside render() function. Because setState() function changes the state of the application and causing a change in the state called the render() function again. So if you write something like this then calling the function stack will go for infinity and application gets the crash.

You can define some variables, perform some operation inside render() function, but never use the setState function. In general cases, We are logging out some variable’s output in the render() method. It is the function that calls in mounting lifecycle methods.

componentDidMount()

after all the elements of the page is rendered correctly, this method is called. After the markup is set on the page, this technique called by React itself to either fetch the data from An External API or perform some unique operations which need the JSX elements.

componentDidMount() method is the perfect place, where we can call the setState() method to change the state of our application and render() the updated data loaded JSX. For example, we are going to fetch any data from an API then API call should be placed in this lifecycle method, and then we get the response, we can call the setState() method and render the element with updated data.

import React, { Component } from 'react';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      data: 'Irie' Dreams'
    }
  }

  getData(){
    setTimeout(() => {
      console.log('The data is fetched');
      this.setState({
        data: 'Hello Dreams'
      })
    }, 1000)
  }
componentDidMount(){
    this.getData();
  }

  render() {
    return(
      <div>
      {this.state.data}
    </div>
    )
  }
}

export default App;

Enter fullscreen mode Exit fullscreen mode

an API call with setTimeOut function is simulated and fetch the data. So, after the component is rendered correctly, componentDidMount() function is called and that call getData() function.

So the method is invoked immediately after the component is mounted. If you load data using api then it right place for request data using api.

componentWillUnmount()

componentWillMount() method is the least used lifecycle method and called before any HTML element is rendered. If you want to see then check out the example mentioned above, we just need to add one more method.
This method immediately executed when the component is unmounted and destroy from the DOM. Means this method is called when a component is being removed from the DOM.

componentDidUpdate()

This method immediately executed on the DOM when the component has been updated. Update occurs by changing state and props. This method is not called for the initial render. This is a good place for compare the current props to previous props.

The method componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state changes. It takes as its first two arguments the previous props and the previous state.

When componentDidUpdate() is good to be used?

componentDidUpdate() is good to be used when we need to call an external API on condition that the previous state and the current state have changed.

The call to the API would be conditional to the state being changed. If there is no state change, no API is called.

In order to avoid an infinite loop, the API call needs to be inside a conditional statement.

. . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player