The Wayback Machine - https://web.archive.org/web/20241126023553/https://www.geeksforgeeks.org/reactjs-lifecycle-components/
Open In App

React Lifecycle

Last Updated : 12 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The React lifecycle is an essential concept for any React developer to understand. Each component in React has a lifecycle that you can monitor and manipulate during its three main phases: Mounting, Updating, and Unmounting. These phases represent the stages a React component goes through from its creation to its removal from the DOM.

React components follow a predictable lifecycle, making it easier for developers to manage data fetching, subscriptions, DOM updates, and other side effects at appropriate times. In this article, we will explore the three phases of the React lifecycle and demonstrate how to use lifecycle methods effectively in class-based components.

React Lifecycle Phases

React Lifecycle is defined as the series of methods that are invoked in different stages of the component’s existence. The definition is pretty simple but what do we mean by different stages? A React Component can go through four stages of its life as follows. 

The React lifecycle is divided into three main phases:

  1. Initialization phase: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.
  2. Mounting Phase: This phase begins when a component is created and inserted into the DOM.
  3. Updating Phase: This occurs when a component is re-rendered due to changes in props or state.
  4. Unmounting Phase: This is the final phase when a component is removed from the DOM.

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

ReactJS Lifecycle of Components

Now let us describe each phase and its corresponding functions.

Phases of Lifecycle in React Components

To gain a deeper understanding of these concepts and enhance your React skills, the React JS Course offered by GeeksforGeeks provides a thorough foundation. This course covers not only the lifecycle methods but also the latest advancements in React, including hooks and their lifecycle effects. By enrolling in this course, you’ll be equipped with the practical skills and knowledge needed to create efficient and effective React applications.

Now lets Move to phases of React components

1. Initialization

In this phase, the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process.

class Clock extends React.Component { 
    constructor(props) 
    { 
        // Calling the constructor of 
        // Parent Class React.Component 
        super(props); 
        
        // Setting the initial state 
        this.state = { date : new Date() }; 
    } 
} 

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 on the webpage. Now React follows a default procedure in the Naming Conventions of these predefined functions where the functions containing “Will” represents before some specific phase and “Did” represents after the completion of that phase. The mounting phase consists of two such predefined functions as described below.

  • constructor
  • static getDerivedStateProps
  • render()
  • componentDidMount()

constructor():

Method to initialize state and bind methods. Executed before the component is mounted.

constructor example:

JavaScript
// Filename - src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hello: "World!" };
    }

    render() {
        return (
            <div>
                <h1>
                    GeeksForGeeks.org, Hello
                    {this.state.hello}
                </h1>
            </div>
        );
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(<Test />);

static getDerivedStateFromProps

Used for updating the state based on props. Executed before every render.

Example:

JavaScript
// Filename - src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hello: "World!" };
    }
    static getDerivedStateFromProps(props, state) {
        return { hello: props.greet };
    }


    render() {
        return (
            <div>
                <h1>
                    GeeksForGeeks.org, Hello
                    {this.state.hello}
                </h1>
            </div>
        );
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(<Test greet="Geeks!"/>);

render() method:

Responsible for rendering JSX and updating the DOM.

render() Example:

JavaScript
// Filename - src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {
    render() {
        return (
            <div>
                <h1>
                    GeeksforGeeks
                </h1>
            </div>
        );
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(<Test />);

componentDidMount() Function

This function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time

componentDidMount() Example:

JavaScript
// Filename - src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hello: "World!" };
    }
    componentDidMount() {
        this.setState({hello:"Geeks!"})
    }
    render() {
        return (
            <div>
                <h1>
                    GeeksForGeeks.org, Hello
                    {this.state.hello}
                </h1>
            </div>
        );
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(<Test />);

3. Updation

React is a JS library that helps create Active web pages easily. Now active web pages are specific pages that behave according to their user. For example, let’s take the GeeksforGeeks {IDE} webpage, the webpage acts differently with each user. User A might write some code in C in the Light Theme while another User may write Python code in the Dark Theme all at the same time. This dynamic behavior that partially depends upon the user itself makes the webpage an Active webpage.

Now how can this be related to Updation? Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on the keyboard, etc. The following are the descriptions of functions that are invoked at different points of the Updation phase.

  • getDerivedStateFromProps
  • setState() Function
  • shouldComponentUpdate()
  • getSnapshotBeforeUpdate() Method
  • componentDidUpdate()

getDerivedStateFromProps:

getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments.

static getDerivedStateFromProps(props, state) {
        if(props.name !== state.name){
            //Change in props
            return{
                name: props.name
            };
        }
        return null; // No change to state
}

setState()

This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the state of a component. You may refer to this article for detailed information.

this.setState((prevState, props) => ({
      counter: prevState.count + props.diff
}));

setState Example:

JavaScript
// Filename - index.js

import React from "react";
import ReactDOM from "react-dom/client";

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }

    increment = () => {
        this.setState((prevState) => ({
            count: prevState.count + 1,
        }));
    };

    decrement = () => {
        this.setState((prevState) => ({
            count: prevState.count - 1,
        }));
    };

    render() {
        return (
            <div>
                <h1>
                    The current count is :{" "}
                    {this.state.count}
                </h1>
                <button onClick={this.increment}>
                    Increase
                </button>
                <button onClick={this.decrement}>
                    Decrease
                </button>
            </div>
        );
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

shouldComponentUpdate()

By default, every state or props update re-renders the page but this may not always be the desired outcome, sometimes it is desired that updating the page will not be repainted. The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not.

shouldComponentUpdate() is invoked before rendering an already mounted component when new props or states are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in the case of forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not.

shouldComponentUpdate(nextProps, nextState)

It returns true or false, if false then render(), componentWillUpdate() and componentDidUpdate() method does not gets invoked.

getSnapshotBeforeUpdate() Method

The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated.

getSnapshotBeforeUpdate(prevProps, prevState)

componentDidUpdate() Function

Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props.

componentDidUpdate(prevProps, prevState, snapshot)

4. Unmounting

This is the final phase of the lifecycle of the component which is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.

componentWillUnmount() Function:

This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

componentWillUnmount() Example:

JavaScript
import React from "react";
class ComponentOne extends React.Component {
    // Defining the componentWillUnmount method
    componentWillUnmount() {
        alert("The component is going to be unmounted");
    }

    render() {
        return <h1>Hello Geeks!</h1>;
    }
}

class App extends React.Component {
    state = { display: true };
    delete = () => {
        this.setState({ display: false });
    };

    render() {
        let comp;
        if (this.state.display) {
            comp = <ComponentOne />;
        }
        return (
            <div>
                {comp}
                <button onClick={this.delete}>
                    Delete the component
                </button>
            </div>
        );
    }
}

export default App;

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.

Implementing the Component Lifecycle methods

Let us now see one final example to finish the article while revising what’s discussed above.

First, create a react app and edit your index.js file from the src folder.

JavaScript
// Filename - src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hello: "World!" };
    }

    componentDidMount() {
        console.log("componentDidMount()");
    }

    changeState() {
        this.setState({ hello: "Geek!" });
    }

    render() {
        return (
            <div>
                <h1>
                    GeeksForGeeks.org, Hello
                    {this.state.hello}
                </h1>
                <h2>
                    <a
                        onClick={this.changeState.bind(
                            this
                        )}
                    >
                        Press Here!
                    </a>
                </h2>
            </div>
        );
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate()");
        return true;
    }

    componentDidUpdate() {
        console.log("componentDidUpdate()");
    }
}

const root = ReactDOM.createRoot(
    document.getElementById("root")
);
root.render(<Test />);

Output: This output will be visible on the http://localhost:3000 on the browser window.React lifecycle example - output



Previous Article
Next Article

Similar Reads

Explain new lifecycle methods in React v16.3
React 16.3 introduced significant updates, deprecating and discouraging the usage of three lifecycle methods—`componentWillReceiveProps()`, `componentWillUpdate()`, and `componentWillMount()` by adding the "UNSAFE_" prefix due to potential misuse and issues in the code. The new Ref API and other changes were also introduced in this update. React 16
3 min read
React JS lifecycle methods order in Mounting
Every component in React has to go through three phases that are Mounting, Updating, and Unmounting. These are called lifecycle methods in react.js. Out of the three, mounting is the first phase in the life cycle. There four methods which come under the mounting phase are: Table of Content Constructor()getDerivedStateFromProps()render()componentDid
4 min read
Mimicking Lifecycle Methods with Hooks in React
React Hooks provides a powerful way to manage state and lifecycle events in functional components. However, if you're transitioning from class components to functional components, you might miss the familiar lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount. Fortunately, you can achieve similar functionality usi
5 min read
Explain Lifecycle Methods of React Components
Lifecycle Methods of React Components are defined as a series of methods that are invoked in different stages of the component's existence. React web apps are actually a collection of independent components which run according to the interactions made with them. Every React Component has a lifecycle of its own. Table of Content Prerequisites for Li
5 min read
Explain the React component lifecycle techniques in detail
React components are the reusable and independent bits of code that help build the user interface of a webpage. Each of these components has various lifecycle methods which are invoked at different stages of their lifecycle. There are 4 stages in the lifecycle of a react component. React Component Lifecycle Techniques1. Initialization: It is the fi
6 min read
NodeJS Program Lifecycle
Node.js is a JavaScript runtime that is built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we need to execute a program written in JavaScript. It uses an event-driven, non-blocking I/O model that makes it most scalable and popular. Non-blocking simply means multiple requests can be processed in parallel. L
4 min read
How a component affects lifecycle of another component after removing in AngularJS ?
In AngularJS, all components are connected with each i.e. they are often inter-dependent. So, If we are attempting to remove one component that can have a ripple effect on the overall lifecycle of another component. The specific effect directly depends on the specific type of components we are removing and how they are connected to each other. When
5 min read
Explain lifecycle of ReactJS due to all call to this.setState() function
In React, the states are used to store data for specific components. These states can be updated accordingly using this.setState function. Updating of state leads to the rendering of UI. Different lifecycle methods are called during these renderings. Lifecycle methods called when the app is loaded first: Constructor()render()componentDidMount()Life
2 min read
Explain lifecycle of component re-rendering due to re-rendering of parent component
React is a javascript library that renders components written in JSX. You can build and render any component as per your usage. States can be updated accordingly using the setState method. Props can be updated only by the parent component. Updating of state and props leads to the rendering of UI. Different lifecycle methods are called during these
2 min read
What are the different phases of ReactJS component lifecycle ?
In React JS, the development of each component involves the use of different lifecycle methods. All the lifecycle methods used to create such components, together constitute the component's lifecycle. They are defined as a series of functions invoked in various stages of a component. There are primarily 4 phases of a lifecycle as follows. Table of
4 min read
What is the Lifecycle of an AngularJS Controller ?
The Lifecycle defines the journey of the application, which it goes through, right from creation to destruction. The lifecycle of AngularJS determines how the data interacts with AngularJS. Understanding the lifecycle enables the developer to more efficiently develop applications with greater code reusability and maintainability. During the lifecyc
6 min read
What is the purpose of the componentDidUpdate lifecycle method ?
React web apps are actually a collection of independent components that run according to the interactions made with them. Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. Prerequisites:NPM & NodeReact JSReact
3 min read
What is the significance of the componentDidMount lifecycle method?
Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. In this article, we will dive into the componentDidMount and see the significance of it. Prerequisites:NPM & NodeReact JSReact JS Class ComponentsWhat is compon
3 min read
Explain the componentDidCatch Lifecycle Method in the Context of Error Boundaries ?
Explore the componentDidCatch lifecycle method in React, designed to manage errors within the component tree effectively. Discover its features, including error containment, graceful handling, and access to error details, through practical demonstrations. Harness the power of error boundaries to fortify your React applications against unexpected er
4 min read
Explain the componentDidCatch Lifecycle method in the Context of Error Handling ?
The componentDidCatch is a lifecycle method in React that helps in handling errors that occur during the rendering of a component's tree. It allows components to catch errors generated by their children components, log those errors, and display a fallback UI instead of crashing the entire application. PrerequisitesNodeJS or NPMReactJSJSXReact JS li
4 min read
Role of Postman in the API development lifecycle.
Postman is an API(application programming interface) development tool which helps to build, test, and modify APIs. Almost any functionality that could be needed by any developer is provided by this tool. It can make various types of HTTP requests(GET, POST, PUT, PATCH). In this article, we will explore the role of Postman in the API development lif
4 min read
Component Lifecycle in Angular
In Angular, Components are the fundamental building blocks of an application. Understanding the lifecycle of these components is crucial for effective Angular Development. Angular provides several lifecycle hooks that allow developers to tap into key moments in a Component’s lifecycle and execute custom logic during those times. Component Lifecycle
4 min read
Create an Activity Indicator in react-native using react-native-paper library
React Native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UIs for both platforms. Prerequisites: Basic
2 min read
React Suite Icon extension React Icons
A React suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React Suite Icon extension React icons. React Icons, contains various popular
3 min read
How to Add MUI React Button Icon in React-Bootstrap ?
In this article, we will learn how to add the mui react button icon in react-bootstrap. Icons can be added in the react-bootstrap by importing the MUI icon component and using it within your React-Bootstrap button. React-Bootstrap is a front-end framework that was designed keeping React in mind. Steps to Create React Application And Installing Modu
2 min read
How to import from React-Select CDN with React and Babel ?
In ReactJS, import from React-Select CDN is not done in a simple way as we do with the npm packages. To use them we need to use directly them in the HTML file. It does not work with the project set-up by creating a react app. Prerequisites:React JSHTML, CSS, JavaScriptSteps to Import React-Select CDN with React and Babel:Step 1: Create index.html w
2 min read
Explain new features of React Memo in React v16.6 ?
React memo is a Higher Order Component (HOC) introduced in React v16.6. As the name suggests, Memo API uses the memoization technique to optimize performance and make the application faster. The Memo API avoids unnecessary re-renders in functional components thereby optimizing the performance of the application. We will see two different examples m
2 min read
What is the difference between react-fetch and whatwg-fetch in React.js ?
React-fetch and Whatwg-fetch are both libraries for making HTTP requests in a React application, but they are used for different purposes and have different features. Table of Content React-fetchWhatwg-fetchDifference between React-fetch and Whatwg-fetchReact-fetch: `react-fetch` is a library offering a higher-order component (HOC) for streamlined
2 min read
Plugin "react" was conflicted between "package.json » eslint-config-react-app
The error Plugin "react" was conflicted between package.json and eslint-config-react-app generally arises when there is a conflict in naming convention or package.json data. However, this is not the only reason for this conflict. Some of the other reasons can be due to a different version or conflict in project dependencies. Error image from Termin
2 min read
How to Zoom in/Zoom out using React-PDF in React JS ?
Zooming in or out in React-PDF within a React JS application is achieved by using the 'scale' prop inside the `<Page />` component. The 'scale' prop accepts decimal values; values greater than 1 zoom in, while values less than 1 zoom out the page. Prerequisites:React JSReact Functional ComponentsSyntax: <page scale = {value} /> // When
2 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
What are React Hooks, and why were they added to React?
React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components, making them more powerful and flexible. Hooks Addr
2 min read
Difference between React.memo() and useMemo() in React.
In React applications, optimizing performance is crucial for delivering a smooth user experience. Two key tools for achieving this are React.memo() and useMemo(). While both help improve performance, they serve different purposes and are used in distinct scenarios. Table of Content What is React.memo() ?What is useMemo() ?Difference Between React.m
3 min read
How does React.memo() optimize functional components in React?
React.memo() is a higher-order component provided by React that can help optimize functional components by reducing unnecessary re-renders. Let's explore how it works and how it optimizes functional components: Table of Content Optimizing with React.memo()When to use React.memo() ?Benefits of memoization using React.memo()How to use React.memo() ?C
4 min read
How to add a divider in react-native using react-native-paper library ?
React native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UI's for both platforms. Prerequisites: Basi
2 min read
Article Tags :
three90RightbarBannerImg