componentDidMount: Side Effects After First Render
You'll learn when and how to use componentDidMount to perform side effects after a class component first appears on screen.
What is componentDidMount?
componentDidMount is a lifecycle method that runs once, immediately after your component finishes its first render and appears in the DOM. Think of it as the "setup zone" where you do things that need the component to exist first—like fetching data from an API, subscribing to events, or manipulating the DOM directly.
Analogy: It's like moving into a new apartment. You don't start unpacking your boxes while the movers are bringing furniture in (that's the render phase). You wait until everything is in place, then you unpack, set up internet, and hang pictures on the wall.
Basic Structure
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = { user: null };
}
componentDidMount() {
// Side effects go here!
// This runs AFTER the first render
fetch(`/api/users/${this.props.userId}`)
.then(response => response.json())
.then(user => this.setState({ user }));
}
render() {
if (!this.state.user) return <div>Loading...</div>;
return <h1>{this.state.user.name}</h1>;
}
}
When to Use It
- Data fetching: API calls that populate your component
- Subscriptions: Setting up event listeners or WebSocket connections
- DOM manipulation: Integrating with third-party libraries that need real DOM nodes
Key Takeaway: componentDidMount runs once after the first render, making it the perfect place for initialization side effects that require the component to exist in the DOM first.