What are Reactjs Lifecycle Methods?

Konfinity
September 14,2020 - 15 min read
What are reactjs lifecycle methods

Every component in React has a definite lifecycle that is constituted of several phases. Mounting, Dismounting and updating along with few others are the phases that form the lifecycle of any and every component in Reactjs.

These phases further consist of built-In methods that are called in a particular order. These built-in methods are popularly called Reactjs lifecycle methods. They perform specific functions in every phase.

We would dwell into the intricacies of every phase and the utility of Reactjs Lifecycle methods but before that let’s get a bird’s eye view. We will take a broad perspective and understand what is Reactjs lifecycle and where the Reactjs lifecycle methods fit in the entire landscape.

Reactjs, essentially a javascript library, is used to create experiences on web. It basically builds excellent user interface for a wide range of applications. Any Reactjs developer would agree that components are one of the most useful features of Reactjs. They are rightly known as the building blocks of React.

The main advantage of components is that they divide the UI interface into independent and reusable bits of code. This division of makes it easier for you to build and maintain applications.

Reactjs component gives birth to others is a specific format known as the Reactjs lifecycle. This makes the whole process simple yet efficient.

Every phase of the lifecycle performs a specific role and contains within them a wide variety of methods. Developers are expected to follow the lifecycle protocol and code within the boundaries of each phase and Reactjs lifecycle methods

The Reactjs lifecycle can be thought of as a defined pathway that coders are required to follow to build applications in the domain of IoT, web development and other fields.

Reactjs lifecycle and its methods let developers build scalable applications in an efficient manner. Reactjs lifecycle methods provide for an impactful coding architecture and better experience while building applications.

We hope now you have some perspective. Next up is a detailed analysis of each and every phase of Reactjs lifecycle and understanding of Reactjs lifecycle methods that come under each phase.

Reactjs Lifecycle Methods

Now that we have understood the importance of Reactjs lifecycle and Reactjs lifecycle methods, let us dwell into its technical implementation.

The Reactjs lifecycle is split into phases and these phases further consist of Reactjs Lifecycle methods.

The first phase is the Initialization phase and as the name suggests, it is the phase where the component gets created an initialized. The properties and the initial state of the component is provided and it is done through a constructor. Constructor(props), is a special Reactjs lifecycle method that gets called whenever a new component is created. It is used for binding the event handlers. Developers cannot cause side effects in this method.

While the initial state and props(properties) have to supplied in this phase, you can always change them later in the lifecycle calling relevan Reactjs lifecycle methods.

Mounting

The next phase of Reactjs lifecycle method is Mounting. In this phase, the component is initialized. It would now be mounted on the Document object model. It is the stage where components are rendered for the first time. There are some built-in Reactjs lifecycle methods that are called when the component is in the Mounting phase.

The method that can be called is componentWillMount(). This is called immediately before the component is rendered. This method is not compulsorily executed, you can call it if you want otherwise it won’t be executed.

The second method is getDerivedStateFromProps() which gets called when component receive new props. If any data is passed on the components or a state change occurs then this method is called. Mostly, this is the method to set the state objects based on the initial props and it also doesn’t causes side effects. In this method, the argument is the state and it returns the objects with the changed state. The method getDerivedStateFromProps() is a static method and hence does not have access to this keyword.It is a rarely used Reactjs lifecycle method.

The next method in line is componentDidMount(). This Reactjs lifecycle method is called after the component and all its child components are rendered in the DOM. In this method, you run statements that require the components to be in the DOM. It is executed only once in the whole lifecycle of a component. Here, you can perform side effects for example interact with the Document object model or perform any ajax calls to load data.

Between componentDidMount() and componentWillMount(), the render() method is compulsorily called. This method actually outputs the component to the DOM.

The example below is the implementation of Reactjs Lifecyle methods in the mounting phase. It may help you in understanding the built-in methods better and how they are actually performed in Reactjs.

Example 1

  • class Lifecycle extends Component {
  • Constructor (props) {
  • Super (props)
  • This.state ={
  • Name: Konfinity
  • }
  • Console.log ('Lifecycle constructor')
  • }
  • static getDerivedStateFromProps( props, state)
  • {
  • Console.log('LifecyclegetDerived FromProps')
  • Return null
  • }
  • ComponentDidMount()
  • {
  • Console.log(‘Lifecycle componentDidMount’)
  • }
  • Render()
  • {
  • Console.log('Lifecycle render')
  • }
  • }

Output

The output of this could would be as follows –

  • Lifecycle getDerivedStateFromProps
  • Lifecycle render
  • Lifecycle componentDidMount

Explanation

In this code, the Reactjs lifecycle methods that we can see are :

In the state, we will simply add the property.

The console.log statements inside the scope of every Reactjs lifecycle method are important to understand the order of execution of each of them in the final output.

As you can see, the constructor is the first method to get executed as it is formed as soon as the component is created. This is the initialization phase where we have supplied the state of the component.

The second Reactjs lifecycle method to be executed is getDerivedStateFromProps. This method gets props and states as arguments and returns the new state or Null. In our example, we have simply returned null.

Render function is the next function to be executed. This Reactjs lifecycle method mounts the component onto the DOM.

The last method to be executed is componentDidMount. This is the final method that is executed after the component is mounts the DOM. It occurs only once in the entire lifecycle of one component and its child.

This is the order of execution of Reactjs lifecycle methods in the mounting phase. The aforementioned code is a simple execution that aims at only making you understand the Reactjs lifecycle and Reactjs lifecycle methods.

Update

After the document is mounted on the DOM, the next phase begins. This phase is the Update phase where a component is updated when it receives a new state or prop.

The next phase is componentShouldupdate(). This phase sounds like a question and actually it is like a question. It executes after the components have received updates and before it would be re rendered in the DOM. The default value is true (the component will be rendered in the DOM) but you can always set it to false.

The next method is render (). This method is called when the component gets updated and it has to re render to the DOM. In this output. The render function is a pure function. It gives the same output for every same input that is passed to the function.

The next method that is called is componentDidUpdate. This is called when component’s update is flushed to the Document Object Model. Basically, it is called after the render () method is executed.

We have seen a practical implementation of all the Reactjs lifecycle methods in the Mounting phase. We have a broad technical overview of the order of execution, the arguments and the utilities of methods in the mounting phase.

Similarly, we urge you to understand all methods in the update phase for yourself. Get creative and play with different Reactjs lifecycle methods and come up with interesting examples to understand the need of each method.

Unmounting

The next phase is the Unmount phase. In this phase the component is about to be removed from the DOM. This Reactjs lifecycle method is invoked immediately before the component is unmounted from the document object model and destroyed. This phase has only one method and that is componentWillUnmount(). After the removal of the component, all its child components also get removed from the DOM tree.

After the component is removed from the DOM the process of garbage collection takes place. An example of a cleanup activity is mentioned below.

  • componentWillUnmount () {
  • this.resetSession ();
  • }

Cleanup activities are important because they improve the overall performance, maintain security and prevent memory leakages.

Error Handling

The next and the final stage is the error handling phase method. It has namely two methods, staticgetDerivedStateFromError(error) and componentDidCatch(error,info).

This phase and its methods are invoked when there is an error either during rendering, in any Reactjs lifecycle method or inside the constructor of any child component.

With this we come to an end of the Reactjs lifecycle and their methods. We have had a brief overview of the lifecycle of components in React and the methods that constitute each and every phase of the lifecycle. Reactjs lifecycle methods have specific utilities that helps in the entire process of building an application.

If you have come here after going through the entire Reactjs lifecycle and all the Reactjs lifecycle methods then we suspect that you are a potential React developer who will go on to build amazing products and create a difference. Let us enlighten you more on React and its stake in the global market.

React is the technology in demand. Businesses across the globe are constantly looking for React developers to help them render excellent experience for their users. It has a huge potential in future. If you are crazy about web development and see yourself grow in this field then React is simply a must-know technology for you.

In case you didn’t know, Konfinity ‘s Web Development Course is developed by experts from IIT DELHI in collaboration with tech company like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

Join the course to master the art of creating web applications by learning latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. You know what’s amazing - no prior coding experienced is required to take up our courses. Start your free trial here.

Chat with us on WhatsApp