Difficulty: Beginner
Explain the React component lifecycle. How do class lifecycle methods map to hooks?
The component lifecycle is one of those foundational concepts that you absolutely need to understand, even though modern React code mostly uses hooks instead of class lifecycle methods. Here's why: hooks are abstractions on top of the lifecycle, and when something goes wrong - when a useEffect fires at the wrong time, when cleanup doesn't work as expected, when re-renders happen unexpectedly - you need to understand what's happening underneath to debug it effectively. Plus, a huge amount of production React code out there is still class-based, and you'll encounter it.
So let's walk through the lifecycle of a React class component. Think of it like the life stages of a living thing: it's born (mounting), it grows and changes (updating), and eventually it dies (unmounting).
Mounting is when the component instance is created and inserted into the DOM for the first time. The methods fire in this order:
Updating happens whenever the component re-renders due to new props, setState, or forceUpdate. The methods fire in this order:
Unmounting is when the component is removed from the DOM:
Now, how does all of this map to hooks? A single useEffect replaces three lifecycle methods. An effect with an empty dependency array is roughly componentDidMount - it runs once after the first render. An effect with specific dependencies is roughly componentDidUpdate for those specific values - it re-runs when they change. And the cleanup function returned from useEffect is componentWillUnmount (plus it runs before each re-run of the effect, which is actually a superpower that class components didn't have - it means your cleanup is always paired with the specific effect run that created it).
But there's a subtle difference to know: useEffect runs asynchronously, after the browser has painted. componentDidMount runs synchronously, before the browser paints. In most cases this doesn't matter, but if you're doing DOM measurements or visual adjustments that must happen before the user sees anything, you need useLayoutEffect, which has the same timing as componentDidMount.
shouldComponentUpdate maps to React.memo for function components. You wrap your function component in React.memo(), and React will skip re-rendering it if its props haven't changed (shallow comparison by default, or you can provide a custom comparison function).
One thing that still requires class components: Error Boundaries. componentDidCatch and getDerivedStateFromError are the only lifecycle methods that have no hooks equivalent. If you need to catch JavaScript errors in a component tree and display a fallback UI, you must write a class component. There have been discussions about adding a useErrorBoundary hook, but as of now, Error Boundaries remain class-only territory.
class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = { user: null, loading: true };
}
componentDidMount() {
// Runs once after first render - fetch data here
fetch(`/api/users/${this.props.userId}`)
.then(res => res.json())
.then(user => this.setState({ user, loading: false }));
}
componentDidUpdate(prevProps) {
// Runs after every update - compare props to avoid infinite loops
if (prevProps.userId !== this.props.userId) {
this.setState({ loading: true });
fetch(`/api/users/${this.props.userId}`)
.then(res => res.json())
.then(user => this.setState({ user, loading: false }));
}
}
componentWillUnmount() {
// Cleanup subscriptions, timers, etc.
console.log('Cleaning up...');
}
render() {
if (this.state.loading) return <p>Loading...</p>;
return <h1>{this.state.user.name}</h1>;
}
}
componentDidMount fires once after mount (API calls). componentDidUpdate fires after each update (must guard with conditions). componentWillUnmount is for cleanup.
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
// Combines componentDidMount + componentDidUpdate
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(user => {
setUser(user);
setLoading(false);
});
// Combines componentWillUnmount
return () => {
console.log('Cleaning up...');
};
}, [userId]); // Re-runs when userId changes
if (loading) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}
One useEffect replaces componentDidMount, componentDidUpdate, and componentWillUnmount. The dependency array controls when the effect re-runs.
// Class: shouldComponentUpdate
class ExpensiveComponent extends React.Component {
shouldComponentUpdate(nextProps) {
// Only re-render if items actually changed
return nextProps.items !== this.props.items;
}
render() {
return (
<ul>
{this.props.items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
}
// Function component equivalent: React.memo
const ExpensiveComponent = React.memo(function({ items }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
});
// Custom comparison
const ExpensiveComponent = React.memo(
function({ items }) { /* render */ },
(prevProps, nextProps) => {
return prevProps.items.length === nextProps.items.length;
}
);
shouldComponentUpdate in class components maps to React.memo in function components. Both prevent unnecessary re-renders by comparing props.
Lifecycle Methods, Class Components, Mounting, Updating, Unmounting