Component Life Cycle and in Action
The component life cycle is the series of stages a React class component goes through: it is created and added to the page (mounting), it re-renders when props or state change (updating), and it is removed (unmounting). Class components expose special methods for each stage, so you can run code at exactly the right moment, such as fetching data after the first render or clearing a timer before the component disappears.
The three phases and their methods
| Phase | Common methods, in order |
|---|---|
| Mounting | constructor, render, componentDidMount |
| Updating | shouldComponentUpdate, render, componentDidUpdate |
| Unmounting | componentWillUnmount |
There are a few rarer ones, such as getDerivedStateFromProps and getSnapshotBeforeUpdate, but the methods above cover most real code.
Seeing the life cycle in action
This clock component uses all three phases. It sets up initial state in the constructor, starts a timer once it is on the page, reacts to a prop change, and cleans up when it leaves.
import React from 'react';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { now: new Date() };
}
componentDidMount() {
this.timerId = setInterval(() => {
this.setState({ now: new Date() });
}, 1000);
}
componentDidUpdate(prevProps) {
if (prevProps.label !== this.props.label) {
document.title = this.props.label;
}
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return (
<p>
{this.props.label}: {this.state.now.toLocaleTimeString()}
</p>
);
}
}
export default Clock;
What belongs in each method
- constructor: call
super(props)first, setthis.statedirectly, and bind handlers if you are not using arrow-function class fields. Do not callsetStatehere or start network requests. - render: return JSX based on props and state, and nothing else. It must be pure, with no timers, requests or
setStatecalls, because React may call it many times. - componentDidMount: the component is now in the DOM. This is the place for fetching data, adding event listeners to
window, or starting intervals. - componentDidUpdate(prevProps, prevState): runs after every re-render except the first. Compare old and new values before doing work.
- componentWillUnmount: undo everything you started in
componentDidMount.
The infinite update loop
The most damaging mistake in this area is calling setState inside componentDidUpdate without a condition. Setting state triggers an update, which calls componentDidUpdate again, which sets state again, and the component re-renders until React stops it with an error. Always wrap that call in a check such as if (prevProps.userId !== this.props.userId).
The second common bug is forgetting cleanup. If the interval above were not cleared, it would keep calling setState on a component that no longer exists, wasting memory and causing warnings in development.
Development mode runs some code twice
Under React's StrictMode in development, React deliberately mounts, unmounts and remounts components, and calls render-phase methods twice. This is meant to expose missing cleanup. If your log shows componentDidMount twice, that is expected; production builds do not do it.
How this maps to hooks
Function components handle the same moments with useEffect. The effect body plays the role of componentDidMount and componentDidUpdate, and the function it returns plays the role of componentWillUnmount. Understanding the class methods makes that mapping much easier, which is useful when you compare the two styles.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.