Author:  Explain ReactJS lifecycle of components

Table of Contents

React web app are actually a collection of independent components, which runs according to the interaction made with them. Every component has its own lifecycle, ReactJS lifecycle of components can be defined as the series of methods that are invoked in a different stage of components.

Hooks allow function components to access in a different way.

During the lifetime of components, there are a series of events called, and for each event you can hook and provide custom functionality. A react component can go through four stages of its life which are:

ReactJS lifecycle of components

  1. Initialization
  2. Mounting
  3. Updating
  4. Unmounting

React provides the developers with a set of predefined functions that if present is invoked around specific events in the lifetime of the component. Developers are supposed to override the functions with the desired logic to execute accordingly.

1. Initialization

In this phase, the developer has to define the props and initial state of the components this is generally done in the constructor of the components. The following code  setting initial state:

this.state = { date : new Date() }; // Setting the initial state

2.Mounting

Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time in the webpage.

Mounting has 4 lifecycle method before the component is mounted in the DOM:

  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount()

1)Constructor

The constructor is the first method that is called when mounting a components.

The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent’s constructor method and allows the component to inherit methods from its parent (React. Component).

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

2)getDerivedStateFromProps()

The getDerivedStateFromProps() method is called right before rendering the element in the DOM.

This is the place to set the state object based on the initial props. It takes the state as an argument and returns an object with changes to the state.

getDerivedStateFromProps() method called before render method:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));

3)render()

render() method you return the JSX that builds the component interface. It is called multiple times with the same input. Here is an example of a simple component with a simple render() method:

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

4)componentDidMount()

This method is the one that you will use to perform API calls or process operations on the DOM.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

3)Updating

The next phase in the lifecycle is when a component update. A component is updated whenever there is a change in the component’s state or props.

When updating you have 5 lifecycle methods before the component is mounted in the DOM:

  • getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpdate

1)getDerivedStateFromProps

This is the first method that is called when a component gets updated. If the component gets updated, the getDerivedStateFromProps() method is called:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));

2)shouldComponentUpdate

This method returns a boolean, true or false. You use this method to tell React if it should go on with the rerendering, and defaults to true. You will return false when rerendering is expensive and you want to have more control on when this happens.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

3)render

The render() method is called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

4)getSnapshotBeforeUpdate 

In this method you have access to the props and state of the previous render, and of the current render. Its use cases are very niche, and it’s probably the one that you will use less.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  getSnapshotBeforeUpdate(prevProps, prevState) {
    document.getElementById("div1").innerHTML =
    "Before the update, the favorite was " + prevState.favoritecolor;
  }
  componentDidUpdate() {
    document.getElementById("div2").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
        <h1>My Favorite Color is {this.state.favoritecolor}</h1>
        <div id="div1"></div>
        <div id="div2"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

5)componentDidUpdate

This method is called when the component has been updated in the DOM. Use this to run any 3rd party DOM API or call APIs that must be updated when the DOM changes.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  componentDidUpdate() {
    document.getElementById("mydiv").innerHTML =
    "The updated favorite is " + this.state.favoritecolor;
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <div id="mydiv"></div>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

4)Unmounting

The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it. Unmounting has only one method: componentWillUnmount

componentWillUnmount

The componentWillUnmount method is called when the component is about to be removed from the DOM.E.g. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }
  delHeader = () => {
    this.setState({show: false});
  }
  render() {
    let myheader;
    if (this.state.show) {
      myheader = <Child />;
    };
    return (
      <div>
      {myheader}
      <buttontype="button" onClick={this.delHeader}>Delete Header</button>
      </div>
    );
  }
}

class Child extends React.Component {
  componentWillUnmount() {
    alert("The component named Header is about to be unmounted.");
  }
  render() {
    return (
      <h1>Hello World!</h1>
    );
  }
}

ReactDOM.render(<Container />, document.getElementById('root'));

Conclusion 

We have so far discussed every predefined function there was in the lifecycle of the component and we have also specified the order of execution of the function.

For more articles –

Share this:
Share

Ankita Nathani

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Popular Products
Popular Posts
The Ultimate Managed Hosting Platform