Introduction to React ComponentDidMount()
The componentDidMount() method is the last step in the Mounting phase. This method is called post mounting. When all the children elements and components are mounted in the Document Object Model (DOM) then we call this method. Calling this method allows us to trigger a new render and provides us access to NativeUI and the children’s refs. componentDidMount() method is the most suitable place to call the setState() method which helps in changing the application’s state and also updates are rendered. In this article, we will understand the componentDidMount() method and it’s working with different examples.
How does React ComponentDidMount() work?
In React, we are provided with a set of hooks that we can use in each phase of the lifecycle. These hooks help us in understanding where the Component is in the Component Lifecycle.
The three phases of the Component Lifecycle are briefed below:
Mounting: In the Mounting phase, the states and the props are configured and the initial UI display is accessed. In this phase, we do the mounting of the children’s components into the DOM.
Updating: In the updating phase, the states, and props are updated. The component spends most of its time in the update phase where all of the new data is incorporated, and the changes with the user actions are defined.
Unmounting: When the component has completed all of the updating, it moves into the Unmounting phase. In this phase, the component gets unmounted from the Native UI stack. When the UI gets changed and the element tree has no matching key to the component, we are in the unmounting phase.
The lifecycle methods are called in a specific order. componentDidMount() is the last step or method used in the Mounting phase. As discussed above, this method is called when all the children elements or components are mounted in the DOM. All the methods in the Mounting phase start working from the top to down except componentDidMount(). ComponentDidMount() methods work from the bottom to the top.
Let’s see the Element Tree below.
This way of working bottom to up ensures that every child has been mounted and the Native UI elements can be accessed by the parents.
Examples to Implement React ComponentDidMount()
Below are the examples mentioned:
Example #1: Basic React ComponentDidMount()
In the example below, firstly text displays. But within a few seconds, new content gets mounted on the previous text and a new window appears with new text. This is done with the help of ComponentDidMount()
The files used to implement the example below are:
App.js
import React from "react";
import "./styles.css";
import Conditional from "./Conditional";
class App extends React.Component {
constructor() {
super();
this.state = {
isLoading: true,
status: "In progression..."
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
isLoading: false,
status: "Completed!"
});
}, 2000);
}
render() {
console.log("Status: ", this.state.status);
return (
<div className="App">
{this.state.isLoading ? <h1>Page is Loading.....</h1> : <Conditional />}
</div>
);
}
}
export default App;
Conditional.js
import React from "react";
function Conditional(props) {
return (
<div>
<h1>
Heyoo! Welcome to EDUCBA.
</h1>
<h2>
This the example of React ComponentDidMount().
</h2>
</div>
);
}
export default Conditional;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
Example #2: Example with Data Fetching Online
In the example below, firstly text appears with “Page is Loading…” then the content is fetched online from https://jsonplaceholder.typicode.com/users and mounted using ComponentDidMount() on the pre-displayed text. After mounting, new content is displayed on the screen.
The files used to implement the below example are:
index.js
import React
, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class Users extends Component {
state = {
users: [],
loading: true
};
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => res.json())
.then(users => {
this.setState({
loading: false,
users
});
});
}
render() {
return (
<div>
{this.state.loading && <p>Page is Loading ...</p>}
<ul>
{this.state.users.map((user, index) => (
<li key={index}>
<h1>{user.name}</h1>
<h4>Email Address: ({user.email})</h4>
<h5>Phone number: {user.phone}</h5>
</li>
))}
</ul>
</div>
);
}
}
function App() {
return (
<div className="App">
<Users />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
}
Output:
Example #3: Example with mounting on third line text
In the example below, whole content remains the same just the text with the line “People Enrolled for our Training:” gets updated after mounting.
The files used to implement the code below are:
index.js
import React from "react";
import ReactDOM from "react-dom";
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
activeUsers: null
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
activeUsers: 1200000
});
}, 2500);
}
render() {
return (
<div>
<h1>Welcome to EDUCBA</h1>
<h2>We are the best Training providers on Latest Emerging Technologies.</h2>
<h3>People Enrolled for our Training: {this.state.activeUsers}</h3>
</div>
);
}
ReactDOM.render(<MyComponent />, document.getElementById("root"));
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
Example #4: Using React ComponentDidMount()
In the example below, the value of the counter is mounted using ComponentDidMount() and updated using componentDidUpdate() when the “Click to Increase Value” button is clicked. The below example is an increment counter.
The files used to implement the code below are:
index.js
import React
, { useState
, useEffect
, Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [counter, setCounter] = useState(1);
useEffect(() => {
console.log("Counter was incremented");
return () => console.log("Counter was cleared");
}, [counter]);
const increment = () => {
setCounter(counter + 1);
};
return (
<div className="App">
<button onClick={increment}>Click to Increase Value</button>
{counter % 3 !== 0 && <Child counter={counter} />}
</div>
);
}
class Child extends Component {
componentDidMount() {
console.log("Child was Mounted");
}
componentDidUpdate() {
console.log("Child was updated");
}
componentWillUnmount() {
console.log("Child was Unmounted");
}
render() {
return (
<div>
<h1>Counter Value</h1>
{this.props.counter}
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
styles.css
.App {
font-family: 'Times New Roman'
, Times
, serif;
text-align: center;
}
Output:
Conclusion
Based on the above article, we understood the use of the componentDidMount() method. We went through its working and the different examples which will help you in understanding how to use this method while building the React applications. I hope this article would make componentDidMount() simpler to understand.
Recommended Articles
This is a guide to React ComponentDidMount(). Here we discuss an introduction to React ComponentDidMount(), working along with programming examples. You can also go through our other related articles to learn more –