Component Lifecycle
Every React component is born, lives, and dies. This journey through mounting, updating, and unmounting is called the component lifecycle. Understanding it is what separates developers who guess at timing bugs from those who know exactly when code runs. In this chapter you'll master every lifecycle phase, every method, their modern useEffect hook equivalents, and see real-world patterns — API fetching, subscriptions, cleanup, and error boundaries — all with clear diagrams and code.
1. What is the Component Lifecycle?
Every React component goes through a predictable sequence of events from the moment it first appears on screen to when it's removed. This sequence is called the component lifecycle.
React divides the lifecycle into three phases. In each phase, React calls specific methods on your component so you can run your own code at exactly the right moment:
2. Full Lifecycle Diagram
Here is the complete sequence of methods React calls in each phase. Methods in purple run in every phase; green = mount only; blue = update only; red = unmount only; orange = error only.
3. Mounting Phase — Component Born
Mounting is the first time a component appears in the DOM. React runs these methods in this exact order, once only:
super(props) first.
Do not call setState here — just assign this.state directly.
setState here triggers a second
render — React batches it before the browser paints.
class UserProfile extends Component {
// 1. constructor — initialise state before render
constructor(props) {
super(props);
this.state = {
user: null,
loading: true,
error: null,
};
}
// 3. componentDidMount — DOM is ready, fetch data
componentDidMount() {
fetch(`/api/users/${this.props.userId}`)
.then(r => r.json())
.then(user => this.setState({ user, loading: false }))
.catch(err => this.setState({ error: err.message, loading: false }));
}
// 2. render — pure snapshot of state → JSX
render() {
const { user, loading, error } = this.state;
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
}
4. Updating Phase — Component Changes
An update is triggered when state changes (setState),
props change (parent re-renders), or
forceUpdate() is called.
React calls these methods in order:
null to change nothing.
Use only when state must be computed directly from props. It's a
static method — no access to this.
Rarely needed in practice; derived state often causes bugs.
true to allow the re-render, false to skip it.
React calls render only if this returns true
(default).
Used for manual performance optimisation in expensive
components.
React.PureComponent does a shallow
comparison automatically.
componentDidUpdate.
Use case: capture scroll position before a list update, then restore it after.
componentDidUpdate(prevProps, prevState) {
// ✅ ALWAYS compare — avoid calling setState unconditionally!
if (this.props.userId !== prevProps.userId) {
// userId prop changed — re-fetch
this.setState({ loading: true });
fetch(`/api/users/${this.props.userId}`)
.then(r => r.json())
.then(user => this.setState({ user, loading: false }));
}
// ❌ NEVER do this — setState without a guard = infinite loop!
// this.setState({ count: this.state.count + 1 });
}
5. Unmounting Phase — Component Dies
When a component is removed from the DOM — because a parent stopped rendering it, a route changed, or a conditional switched to false — React calls one final method.
setState here — the
component
is about to be removed; a new render would be wasted.
class LiveFeed extends Component {
componentDidMount() {
// Set up things that need cleanup
this.timer = setInterval(() => this.fetchLatest(), 5000);
this.ws = new WebSocket('wss://api.example.com/feed');
window.addEventListener('resize', this.handleResize);
document.addEventListener('keydown', this.handleKey);
}
componentWillUnmount() {
// ✅ Cancel / remove everything set up in componentDidMount
clearInterval(this.timer); // stop the timer
this.ws.close(); // close WebSocket
window.removeEventListener('resize', this.handleResize);
document.removeEventListener('keydown', this.handleKey);
// Abort any in-flight fetch if using AbortController
this.abortCtrl?.abort();
}
render() { return <div>Live Feed</div>; }
}
6. Error Boundaries — Catching Render Errors
If a component throws an error during rendering, React normally unmounts the entire tree — the whole app goes blank. Error Boundaries catch render errors in their subtree and show a fallback UI instead. They are the only place where you must use class components in modern React.
info object with
componentStack.
Good for logging — send to Sentry, LogRocket, etc.
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, message: '' };
}
// 1. Called during render — update state to show fallback
static getDerivedStateFromError(error) {
return { hasError: true, message: error.message };
}
// 2. Called after render — log to monitoring
componentDidCatch(error, info) {
console.error('Error caught:', error);
console.error('Component stack:', info.componentStack);
// sendToSentry(error, info); ← log to error monitoring
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong 😔</h2>
<p>{this.state.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage — wrap any subtree you want to protect
<ErrorBoundary>
<UserDashboard />
</ErrorBoundary>
7. Lifecycle → useEffect Equivalents
In functional components, the useEffect
hook
replaces all three lifecycle phases in one consistent API.
The key is the dependency array:
| Class Lifecycle Method | useEffect Equivalent | When it runs |
|---|---|---|
componentDidMount()
|
useEffect(() => {'{ }'}, [])
|
Once, after first render |
componentDidUpdate(prev, state)
|
useEffect(() => {'{ }'}, [dep])
|
After render when dep changes |
componentDidUpdate() (any)
|
useEffect(() => {'{ }'})
|
After every render |
componentWillUnmount()
|
useEffect(() => {'{ return () => cleanup }'}, [])
|
Cleanup function on unmount |
didMount + willUnmount
|
useEffect(() => {'{ setup; return cleanup }'}, [])
|
Setup on mount, cleanup on unmount |
import { useState, useEffect } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// ✅ componentDidMount + componentDidUpdate(prevProps.userId ≠ userId)
useEffect(() => {
const controller = new AbortController();
setLoading(true);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(r => r.json())
.then(d => { setUser(d); setLoading(false); })
.catch(e => {
if (e.name !== 'AbortError') { setError(e.message); setLoading(false); }
});
// ✅ componentWillUnmount — cancel in-flight request
return () => controller.abort();
}, [userId]); // re-runs when userId changes
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error}</p>;
return <div><h2>{user?.name}</h2></div>;
}
componentDidMount. Put each concern in its own effect with
its own dependencies.
8. Common Lifecycle Pitfalls
Most lifecycle bugs come from the same few mistakes. Here are the ones every React developer hits:
setState inside componentDidUpdate without a condition triggers
another update, which calls componentDidUpdate again
— forever. Always compare prevProps/prevState first.componentDidMount may resolve after the component
unmounts. Calling setState on an unmounted component
causes a warning. Use an AbortController or an isMounted flag to cancel.useEffect but don't list it in the dependency array,
the effect captures a stale value from the first render. Always include
every value read inside the effect in its deps.fetch(), localStorage.setItem(), or modifying the DOM directly
inside render() is wrong. The render must be pure —
side effects belong in componentDidMount or useEffect.setInterval in componentDidMount without a matching removal in componentWillUnmount accumulates handlers and causes
bugs when the component mounts/unmounts repeatedly.setState here causes a warning. In the constructor,
assign this.state = {'{...}'}
directly; call setState only after mounting.
Explore More Tutorials
1. constructor() — if defined, runs first. Initialises state and binds methods.
2. static getDerivedStateFromProps() — runs before render on mount and every update. Returns state update or null.
3. render() — returns JSX. Must be pure.
4. componentDidMount() — runs after the component is inserted into the DOM. Safe to fetch data and add subscriptions here.
Note:
render() runs before the DOM is ready;
componentDidMount() runs after the DOM is ready. This distinction
matters for DOM measurements and API calls.
componentDidUpdate runs after every update — every time
any state or prop changes.
If you call
setState() inside it without a guard, it triggers another
update → which calls componentDidUpdate again → which calls
setState again → infinite loop.
By comparing
prevProps.userId !== this.props.userId, you ensure your code
only runs when the specific thing you care about actually changed. The comparison is the
guard that breaks the loop.
useEffect(() => {'{ setup(); return () => cleanup(); }'}, [])
React calls the returned cleanup function when the component unmounts (or before the effect re-runs if dependencies changed).
Rule: If your useEffect sets something up (event listener, timer, subscription, WebSocket), the return function should tear it down.
componentDidCatch() and
getDerivedStateFromError(). As of React 18, there is no Hook
equivalent for these two methods.
The React team has acknowledged this gap. A
use() API and improved error
handling are being discussed for future versions, but for now Error Boundaries remain
the one case where you must write a class component in new code.
In practice, most projects have just one or two Error Boundary class components wrapping major sections (like the whole app, or the main content area).
useEffect(() => {'{ }'}, []) map to in class
components?setInterval in
componentDidMount. What must you do in componentWillUnmount?- Every React component goes through 3 lifecycle phases: Mounting (born), Updating (lives), and Unmounting (dies).
- Mounting order: constructor → getDerivedStateFromProps → render → componentDidMount. The DOM is only available after render completes.
componentDidMount()is the right place for API calls, subscriptions, timers, and DOM measurements.componentDidUpdate(prevProps, prevState)reacts to changes. Always compare previous values before calling setState to avoid infinite loops.componentWillUnmount()is cleanup time. Every setup in componentDidMount needs a corresponding teardown here — timers, listeners, WebSockets.- Error Boundaries use
getDerivedStateFromError()to show fallback UI andcomponentDidCatch()to log errors. They must be class components. - useEffect with empty deps
[]= componentDidMount. With deps = componentDidUpdate. Returned cleanup function = componentWillUnmount. - Common pitfalls: setState in componentDidUpdate without guard (infinite loop), no cleanup (memory leak), side effects in render (impure), missing useEffect deps (stale closure).
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.