We now have a youtube channel. Subscribe!

ReactJS | Component Life Cycle

ReactJS | Component Life Cycle


Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about ReactJS Component Life Cycle.

In React, component's Life cycle represents the various stages of the component during its existence. React gives callback function to attach functionality in every stages of the React life cycle. Let us discuss the life cycle (and the related API) of a React component in this tutorial.

Life Cycle API

Each React component has three different stages -

  • Mounting - Mounting represents the rendering of the React component in the given DOM node.
  • Updating - Updating represents the re-rendering of the the React component in the specified DOM node during the state changes/updates.
  • Unmounting - Unmounting represents the removal of the React component.

React gives a collection of life cycle events (or callback API) for attaching functionality, which will be executed during the different stages of the component. The visualization of life cycle and the sequences in which the life cycle events(APIs) are invoked is shown below -

React Life Cycle


constructor()

Invoked during the first construction phase of the React component. Used to set initial state and properties of the component.

render()

render() is invoked after the construction of the component is completed. It renders the component in virtual DOM instance. This is specified as mounting of the component in the DOM tree.

componentDidMount()

componentDidMount() is invoked after the initial mounting of the React component in the DOM tree. It is the best place to call API endpoints and to execute network requests. In our clock component, setInterval function can be set here to update the state (current date and time) for every second.

componentDidMount() { 
   this.timeFn = setInterval( () => this.setTime(), 1000); 
}

componentDidUpdate()

This is similar to componentDidMount() but invoked during the update phase. Network request can be done during this phase but only when there is difference in component current and previous properties.

The syntax of the API is as follows -

componentDidUpdate(prevProps, prevState, snapshot)

Here,

  • prevProps - Is the previous properties of the component.
  • prevState - Is the previous state of the component.
  • snapshot - Current rendered content.

componentWillUnmount()

Invoked after the component is unmounted from the DOM. This is a good place to clean up the object. In our clock example, we can stop updating date and time in this phase.

componentDidMount() { 
   this.timeFn = setInterval( () => this.setTime(), 1000); 
}

shouldComponentUpdate()

Invoked during the update phase. It is used to specify if the components should update or not. If it returns false, then the update will not happen.

The syntax is as follows -

shouldComponentUpdate(nextProps, nextState)

Here,

  • nextProps - Upcoming properties of the component.
  • nextState - Upcoming state of the component.

getDerivedStateFromProps

This callback API is invoked during both the initial and update phase and just before the render() method. It is used to return the new state object. It's hardly used where changes in the properties leads to state change. It is mostly used in animation context where the various stages of the component is needed to do smooth animation.

The syntax of the API is as follows -

static getDerivedStateFromProps(props, state)

Here,

  • props - Current properties of the component.
  • state - Current state of the component.

This is a static method and does not have access to this object.


getSnapshotBeforeUpdate

Invoked just before the rendered content is committed to DOM tree. It's mainly used to get some data about the new content. The data returned by this method will be passed to the componentDidUpdate() method. For example, it is used in maintaining the user's scroll position in the newly created content. It returns the user scroll position. The scroll position is used by componentDidUpdate() to set the scroll position of the output in the actual DOM.

The syntax of the API is a follows -

getSnapshotBeforeUpdate(prevProps, prevState)

Here,

  • prevProps - Previous properties of the component.
  • prevState - Previous state of the component.

Working Example of Life Cycle API

Let's use life cycle api in our react-clock-app application.

Open react-clock-hook-app in your favorite editor.

Next, open src/components/Clock.js file and start editing.

Next, remove the setInterval() method from the constructor.

constructor(props) { 
   super(props); 
   this.state = { 
      date: new Date() 
   } 
}

Next, add the componentDidMount() method and call setInterval() to update the date and time every second. Also, store the reference to stop updating the date and time later.

componentDidMount() { 
   this.setTimeRef = setInterval(() => this.setTime(), 1000); 
}

Next, add componentWillUnmount() method and call clearInterval() to stop the date and time update calls.

componentWillUnmount() { 
   clearInterval(this.setTimeRef) 
}

Now, we have updated the clock component and the complete code of the component is given below -

import React from 'react';

class Clock extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         date: new Date()
      }      
   }
   componentDidMount() {
      this.setTimeRef = setInterval(() => this.setTime(), 1000); 
   }
   componentWillUnmount() {
      clearInterval(this.setTimeRef)
   }
   setTime() {
      this.setState((state, props) => {
         console.log(state.date);
         return {
            date: new Date()
         }
      })
   }
   render() {
      return (
         <div>
            <p>The current time is {this.state.date.toString()}</p>
         </div>
      );
   }
}
export default Clock;

Next, open index.js file and use setTimeout() to remove the clock from the DOM after five seconds.

import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './components/Clock';

ReactDOM.render(
   <React.StrictMode>
      <Clock />
   </React.StrictMode>,
   document.getElementById('root')
);
setTimeout(() => {
   ReactDOM.render(
      <React.StrictMode>
         <div><p>Clock is removed from the DOM.</p></div>
      </React.StrictMode>,
      document.getElementById('root')
   );
}, 5000);

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.

The clock will be displayed for five seconds and then, it is going to be removed from the DOM. By checking the console log, we can find that the cleanup code is well executed.



Life Cycle API in Expense Manager App

Let us include life cycle api in the expense manager and log it whenever api is called. This will give insight about the life cycle of the component.

Open expense-manager application in your favorite editor.

Next, update the react ExpenseEntryItemList component with the below methods.

componentDidMount() {
   console.log("ExpenseEntryItemList :: Initialize :: componentDidMount :: Component mounted");
}
shouldComponentUpdate(nextProps, nextState) {
   console.log("ExpenseEntryItemList :: Update :: shouldComponentUpdate invoked :: Before update");
   return true;
}
static getDerivedStateFromProps(props, state) {
   console.log("ExpenseEntryItemList :: Initialize / Update :: getDerivedStateFromProps :: Before update");
   return null;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
   console.log("ExpenseEntryItemList :: Update :: getSnapshotBeforeUpdate :: Before update");
   return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
   console.log("ExpenseEntryItemList :: Update :: componentDidUpdate :: Component updated");
}
componentWillUnmount() {
   console.log("ExpenseEntryItemList :: Remove :: componentWillUnmount :: Component unmounted");
}

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.

Next, check the console log. It will show the life cycle api during initialization phase as it is shown below.

ExpenseEntryItemList :: Initialize / Update :: getDerivedStateFromProps :: Before update 
ExpenseEntryItemList :: Initialize :: componentDidMount :: Component mounted

Next, remove an item and then, check the console log. It will show the life cycle api during the update phase as shown below.

ExpenseEntryItemList :: Initialize / Update :: getDerivedStateFromProps :: Before update 
ExpenseEntryItemList.js:109 ExpenseEntryItemList :: Update :: shouldComponentUpdate invoked :: Before update 
ExpenseEntryItemList.js:121 ExpenseEntryItemList :: Update :: getSnapshotBeforeUpdate :: Before update 
ExpenseEntryItemList.js:127 ExpenseEntryItemList :: Update :: componentDidUpdate :: Component updated

Lastly, remove all the life cycle api as it may obstruct the application's performance. Life cycle api should be made use of only if the situation demands.


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about ReactJS Component Life Cycle using React Hooks.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain