Open In App

Explain lifecycle of component re-rendering due to re-rendering of parent component

Improve
Improve
Like Article
Like
Save
Share
Report

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 renderings.

Approach: We will create a UI that will re-render a child component due to parent re-rendering. Users can interact with the UI and click on the button to trigger an event to call this.setState through this. Users can view all the lifecycle methods mentioned above in the console view.

Steps to Create React Project:

Step 1: create a react app

npx create-react-app project_name

Step 2: Move into the project directory

cd project_name

Project Structure:

Project Structure

Example: Let us create a parent and child component. We will create a button that sends a call to update the state through this.setState in the parent component. The same state is passed as prop to child component. We will be able to see the lifecycle methods due to this re rending of both parent and child.

Javascript




import React from "react";
 
class Child extends React.Component {
    constructor() {
        super();
        console.log("Child Constructor called");
    }
 
    componentDidMount() {
        console.log(" Child componentDidMount called");
    }
 
    componentDidUpdate() {
        console.log("Child componentDidUpdate called");
    }
    render() {
        console.log("Child render called");
        return (
            <p>{this.props.message}</p>
        );
    }
}
 
class App extends React.Component {
    constructor() {
        super();
        this.state = {
            message: "initial state"
        }
        console.log("Parent Constructor called");
    }
 
    componentDidMount() {
        console.log("Parent componentDidMount called");
    }
 
    componentDidUpdate() {
        console.log("Parent componentDidUpdate called");
    }
 
    call() {
        this.setState({ message: "state updated" })
    }
 
    render() {
        console.log("Parent render called");
 
        // Rendering a button
        return (
            <div style={{ margin: 100 }}>
                <button onClick={() => { this.call() }}>
                    Click to update state!
                </button>
 
                <p>{this.state.message}</p>
 
                <Child message={this.state.message} />
            </div>
        );
    }
}
export default App;


Step to run the application: Open the terminal and type the following command.

npm start

Output: Localhost running on http://localhost:3000/

Output



Last Updated : 20 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments