Lifecycle of Components in React Js

Every React Component has a unique lifecycle, which is the collection of functions that are called at various points throughout the component’s lifespan.

Although the description is rather simple, what do we mean by distinct stages? A React Component can go through the following four stages throughout its life.

Initialization: At this stage, the component is built using the supplied Props and in its initial state. A component class’s function Object() { [native code] } is where this is done.

Mounting: The step of rendering the JSX that the render method itself returned is known as mounting.

Updating: A component’s state is updated during the updating stage, which also involves repainting the application.

Unmounting: As the name implies, unmounting is the stage in the lifecycle of a component at which time it is taken off the page.

Let’s now go over each phase and its associated functions.

Functions of each Phase of Lifecycle

Initialization:

The developer must specify the component’s props and initial state during this step.

Typically, this is done in the function Object() { [native code] } of the component. The initialization procedure is described in the following line of code.

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() }; 
    } 
}

The step of the component lifecycle known as mounting occurs after initialization is complete and the component is mounted on the DOM and initially rendered on the website.

Now that these preset functions are predefined, React follows a default naming convention where functions containing “Will” represent before a specific phase and functions containing “Did” represent after the conclusion of that phase.

The mounting step consists of the following two preset tasks.

componentWillMount() Function: As its name implies, this method is called once just before the component is mounted on the DOM, or before the render() function is run for the first time.

componentDidMount() Function: Like the preceding function, this one is called once after the render() function is run for the first time, that is, immediately after the component is mounted on the DOM.

Update:

The JavaScript package React makes it simple to develop Active web pages. Active web pages today are particular pages that act in accordance with their user.

Take the GeeksforGeeks IDE Website as an illustration; each user has a different experience with the website.

At the same session, User A might write some Python code in the Dark Theme and User B might write some C code in the Light Theme.The website is an Active webpage because of this dynamic activity that partly depends on the user.

Now tell me how this relates to updating. A component’s states and properties are altered during the update phase, which is followed by some user actions like clicking or pushing a keyboard key. The functions that are described below are called upon at various times during the updating phase.

componentWillReceiveProps() Function: The componentWillReceiveProps() function is independent of States and is only available for Props.

Prior to reassigning a mounted component’s props, this function is called. The new set of Props, which might or might not be the same as the original Props, is supplied to the function.

Checking is therefore a necessary step in this case. A sample use-case is shown in the following line of code.

componentWillReceiveProps(newProps) 
{ 
    if (this.props !== newProps) { 
        console.log(" New Props have been assigned "); 
        // Use this.setState() to rerender the page. 
    } 
}

setState() Function:This function can be directly called at any time and is not specifically a Lifecycle function. The status of a component can be updated using this function. For further details, please see this article.

shouldComponentUpdate() Function: Every state or prop update by default causes the page to be re-rendered, however this may not always be the desired result.

In some cases, it is preferable to update the page without having it repainted.

By informing React if the component’s output will be impacted by the change or not, the shouldComponentUpdate() Function satisfies the requirement.

When new props or state are being received, shouldComponentUpdate() is called before rendering an already mounted component.

The further steps of rendering will not be done if returned false. ForceUpdate prevents the use of this function ().

The Function returns whether to re-render or not after receiving the updated Props and new State as arguments.

componentWillUpdate() Function:As the name implies, this function is called once before the render() function is executed following the updating of State or Props, i.e., before the component is rerendered.

componentDidUpdate() Function: Similar to the previous function, this one is called once once the component is rerendered, that is, after any State or Prop updates have been made.

Unmounting:

This is the last stage of the component’s lifespan, which is the stage where the component is unmounted from the DOM. This phase only contains the following function.

componentWillUnmount() Function:This function is called once before the component is really unmounted from the DOM, which signifies the end of the lifetime. The component is then removed from the page.

Each predefined function that existed in the component’s lifecycle has been covered in detail thus far, and the execution order of each function has also been determined. To wrap off the piece and update the previously stated material, let’s look at one more example.

Create a react app first, then edit the index.js file in the src folder.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
  
class Test extends React.Component { 
    constructor(props) 
    { 
        super(props); 
        this.state = { hello : "World!" }; 
    } 
  
    componentWillMount() 
    { 
        console.log("componentWillMount()"); 
    } 
  
    componentDidMount() 
    { 
        console.log("componentDidMount()"); 
    } 
  
    changeState() 
    { 
        this.setState({ hello : "Himani!" }); 
    } 
  
    render() 
    { 
        return ( 
            <div> 
            <h1>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; 
    } 
  
    componentWillUpdate() 
    { 
        console.log("componentWillUpdate()"); 
    } 
  
    componentDidUpdate() 
    { 
        console.log("componentDidUpdate()"); 
    } 
} 
  
ReactDOM.render( 
    <Test />, 
    document.getElementById('root'));

Submit a Comment

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

Subscribe

Select Categories