Mounting in React Lifecycle
Expert-Level Explanation
Mounting in React refers to the process of adding components to the DOM. This phase includes several key lifecycle methods:
constructor: This is the first method called in the mounting phase. It's used for initialising states and binding event handlers. The constructor is called before the component is mounted.
static getDerivedStateFromProps: This method is invoked right before rendering. It's used for updating the state in response to prop changes, resulting in a re-render.
render: The
render
method is responsible for describing the view to be rendered to the DOM. It's a pure function, meaning it doesn't interact with the browser or change the component state.componentDidMount: This method is called after the component is mounted in the DOM. It's commonly used for making API calls, setting up subscriptions, or interacting with the DOM.
Creative Explanation
Think of mounting a React component as setting up a stage for a play.
constructor: building the stage and setting up the backdrop.
static getDerivedStateFromProps: Adjusting the lighting and props on the stage based on the script's requirements.
render: The actors (UI elements) take their places according to the scene's script.
componentDidMount: The curtain rises, and additional effects like music or background animations start.
Practical Explanation with Code
An example of a class component using these methods:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}
static getDerivedStateFromProps(props, state) {
if (props.source !== state.lastSource) {
return {
data: fetchData(props.source),
lastSource: props.source
};
}
return null;
}
render() {
return <div>{this.state.data}</div>;
}
componentDidMount() {
this.setState({ data: fetchData(this.props.source) });
}
}
function fetchData(source) {
// Fetch data from the source
}
Real-World Example
In a news app, when a user opens an article, the Article
component goes through the mounting phase. The constructor
sets initial state (e.g., loading status),getDerivedStateFromProps
updates the state if the article ID changes, render
method displays the article or a loading spinner, and componentDidMount
fetches the article content and updates the state.