Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconReact Component Lifecycle: What Do You Need To Know [2024]

React Component Lifecycle: What Do You Need To Know [2024]

Last updated:
5th Oct, 2022
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
React Component Lifecycle: What Do You Need To Know [2024]

In React, the application is divided into the smallest possible pieces known as Components. Components can be presentational or container. 

When we talk about presentational components, they have no logic. They are embedded inside the components; it only has the UI.

Container components are the ones that use presentational components and have business logic in the component. Such components often have to keep local state objects to achieve one of the many use cases they might be responsible for. These components use presentational components as child components and pass on data by using various props.

React allows you to have either class or functional components. A prevalent pattern used in the react ecosystem is that the presentational component is a functional type of component, and container components are class type. 

Ads of upGrad blog

Check out our free courses to get an edge over the competition.

The react lifecycle shows the exact process through which components go through, and the reason behind the react component lifecycle.

Functional Components

These are ones having no state, and only manipulations using the props are done.

All component lifecycle methods or the setState cannot be used or accessed inside such components.

Check out upGrad’s Java Bootcamp

Checkout: React Project Ideas

Class Components

These components can have local state, and they have access to lifecycle methods and setState.

A typical class component in react looks like:- 

The component lifecycle has three phases:-

  1. Mounting 
  2. Updating 
  3. Unmounting

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Mounting

When any component is created and inserted into DOM(Document Object Model), the methods used are:

●      constructor()

●      static getDerivedStateFromProps()

●      render()

●      componentDidMount()

Explore our Popular Software Engineering Courses

Updating

When the prop or state supplied to a component is changed, the component’s re-render is also known as the updating phase. In this phase, given below are the following lifecycle methods which get called:

● static getDerivedStateFromProps()

● shouldComponentUpdate()

● render()

● getSnapshotBeforeUpdate()

● componentDidUpdate()

Read: Vue vs React: Difference Between Vue and React

Unmounting

This method is called during the unmounting of any component:-

● component willUnmount()

It is the last function to be invoked before the document object model gets destroyed. It works as the clean up for any element constructed during componentWillMount.

For error handling purpose in the component, there are few methods reserved:-

● static getDerivedStateFromError()

componentDidCatch()

Commonly used lifecycle methods explained in detail:-

● constructor(props)

This lifecycle method is used during the mounting phase of components. One can have a local state object declared here. The super(props) is called inside the constructor before any other statement; otherwise, an error occurs while accessing this.props.

If one does not aim to declare the local state object or bind the event handler to the instance, there is no need to write the components’ lifecycle method.

The calling state in the constructor() is not advised as it would trigger re-render before the previous cycle is ended.

Constructor() is the only place where one can directly assign the state. Otherwise, if there is a need to change the state or assign something inside it, this.setSate should be used.

In-Demand Software Development Skills

●  render()

Inside this method components, the JSX part is written. JSX is similar to HTML but is an extended syntax of javascript. When we are using JSX, we can also use Javascript expressions inside the render method.

Any parent components’ render() method may have child components inside it. All following the composition pattern, which is the base of react components.

Whenever the parent’s render method gets called, the render starts for child components as well, and the parent render is complete only after the entire child render is completed. 

The render method is a required method; without this, the component cannot be made as this is the only place where the view part of a component can be written.

The render method is pure; this means it cannot modify the state inside it.

For any component in the updating phase, the re-render for a particular component will happen or not may depend on shouldComponentUpdate() life cycle method return type or use.

Having API calls and any interaction with the browser inside this method is not advised, and it will throw an error.

componentDidMount()

This method is invoked immediately after the component is mounted. Now DOM is available for further manipulations. One can call setState inside this method. 

Also, the interaction with browser or API calls can be made from here.

This method is only called once, which is during creation time. The method won’t run in any further re-render part, and the logic inside it will also not run.

componentDidUpdate()

This is the same as the componentDidMount.; one can get an error with the only difference that this is only called when the re-render of a component occurs. This method is not called for the initial render.

The setState and side effects can be done inside this method. But the setState needs to be wrapped in a condition; otherwise, one might end up in the render infinite loop, and the render would never end.

Also componentDidUpdate will not be called if the shouldComponentUpdate() returns false.

componentWillUnmount()

This method is called when the unmounting phase of a component is going on.

Inside the method, ideally, the removal of event handlers and cleanup of memory can be achieved.

The setState() function should not be called inside this as it causes the re-render of a component.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

 

shouldComponentUpdate()

While developing react applications, there are often cases when one has to avoid unnecessary re-render of components. To achieve this in-class component, one has the method mentioned above. If this method returns false, then the re-render of the component and its child components will not happen.

The previous props can be checked and compared with new props supplied to ensure no change then return false.

Calling the setState() method inside this is not advised as again, it would cause re-render.

Also, side effects should not be carried out inside this method.

There is also another alternative to this method. One can use React.pureComponents while extending the class. This is much more stable and reliable than the shouldComponentUpdate().

Last but not least, there exist error boundaries type of react components that are present to catch the errors.

One has to wrap the component with the error boundary component simply.

Inside this special component, there are two lifecycle methods used:-

  1. static getDerivedStateFromError() 
  2. componentDidCatch()

Both of them are called if any descendant component throws an error.

The first one is called during the render phase, so no side effects are allowed inside it. The second one is called during the commit phase, so side effects are allowed inside it.

Explore Our Software Development Free Courses

Also Read: ReactJS Developer Salary in India

Ads of upGrad blog

Learn Software Engineering Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Conclusion

The react component lifecycle adds complexity to the code, but the systematic execution and manipulation done through the methods seem quite appealing from the developer’s perspective. React lifecycle lets one restructure or manipulate the components.

If you’re interested to learn more about react, full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What are the disadvantages of using the React library?

The React library of JavaScript keeps on coming up with its updates. When it is a progressive thing, sometimes it becomes difficult for the developers to keep on adjusting to the changes that happen from time to time. Many users do complain that the library has poor documentation. The JavaScript extension seems like an advantage because it makes it easier for a user to carry out the tasks, but it is complex for someone new to get used to it due to its complex nature.

2What are the major pros of using the React library over Plain JS?

The React library sets various rules to carry out the development process; however, it is not the same case for web development in Plain JavaScript: there are no pre-defined rules. When the developer works using Plain JS, you cannot break down the components in any application, unlike in React library of JavaScript. React always makes sure your app’s components get split up. Another difference between ReactJS and Plain JS is how both the libraries react to the user interaction.

3What are the pros of using the React library?

Since the React library comes with training resources and tutorials, it is easy for a newbie to learn it. Also, it has an open-source JavaScript UI embedded in it, making it easier for the user to carry out every task. If you plan to create a web application with HTML strings, it will require you to do a lot of coding, but the react library of JavaScript helps overcome this issue. Instead of a lot of coding, it offers a lot of functionality. React is user-friendly for the developers as it provides many handy tools, making it easier for the developers to understand the tasks well.

Explore Free Courses

Suggested Blogs

Top 7 Node js Project Ideas & Topics
31584
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46947
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers & Experienced]
901332
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners & Experienced]
52128
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers & Experienced]
909209
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34763
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers & Experienced]
902394
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26264
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions & Answers [2024]
4394
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon