Explain lifecycle of component re-rendering due to re-rendering of parent component
React is a UI library that renders components written in JSX. You can build and render any components as per your usage. React.js introduces the concept of states and props. States are used to store data for specific components. Props are used to pass data from parent components to child components. States can be updated accordingly using set State 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.
Lifecycle methods called when app is loaded first:
- Constructor() method
- render() method
- componentDidMount() method
Lifecycle methods called when this.setState is called:
- render() method
- componentDidUpdate() method
Approach: Let us create a React project and then 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.
Creating React Project:
Step 1: To create a react app, you need to install react modules through npx command. “npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.
npx create-react-app project_name
Step 2: After creating your react project, move into the folder to perform different operations.
Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new component user makes or the code changes, we will be performing will be done in the source folder.
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. Thus, the state will update and trigger both parent and child components to rerender. We will be able to see the lifecycle methods due to this re rending of both parent and child.
Filename : App.js
Step to run the application: Open the terminal and type the following command.
Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the console. Appropriate functions are called when the state is updated. First, the initial lifecycle methods of child and parent can be seen when the UI loads for the first time. Then as the state updates, both of them get re-rendered and appropriate lifecycle methods are called.
Please Login to comment...