🚀 Mastering componentDidMount
in React.js (Class-Based) – The Ultimate 2025 Guide
React provides various lifecycle methods, and componentDidMount
is one of the most essential lifecycle methods in class-based components. In this guide, we'll explore how it works and where it's used.
🔍 What is componentDidMount
?
componentDidMount
is a lifecycle method in React that is called once a component is mounted (inserted into the DOM). It's primarily used for:
- Fetching data from an API.
- Setting up subscriptions.
- Interacting with the DOM.
📌 Example: Using componentDidMount
to Fetch Data
Let's build a simple React class-based component that fetches data from an API and displays it.
import React, { Component } from 'react';
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
users: []
};
}
// componentDidMount runs after the component is inserted into the DOM
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {
this.setState({ users: data });
})
.catch(error => console.log('Error fetching users:', error));
}
render() {
return (
User List
{this.state.users.map(user => (
- {user.name}
))}
);
}
}
export default UserList;
🛠️ How This Works
- We initialize an empty
users
array in the state.
- When the component is mounted,
componentDidMount
is executed.
- It fetches user data from the API and updates the state.
- React re-renders the component, displaying the fetched users.
✅ When to Use componentDidMount
?
- Fetching data from an API.
- Setting up event listeners (e.g., WebSocket connections).
- Manipulating the DOM (e.g., integrating third-party libraries).
⚠️ Best Practices
- Always handle errors in API requests.
- Use
componentWillUnmount
to clean up listeners or subscriptions.
- For complex cases, consider React Hooks (
useEffect
in functional components).
🎯 Conclusion
The componentDidMount
method is essential in class-based components for executing logic after the component is rendered. If you're using React Hooks, you can achieve the same behavior with useEffect
with an empty dependency array.