Component Lifecycle
Mounting, updating, and unmounting phases, and how hooks map to the old lifecycle methods.
What you'll learn
- The three phases: mount, update, and unmount
- How useEffect maps to lifecycle phases
- The dependency array as a lifecycle control
- Migrating mental models from class lifecycle methods to hooks
Concept
The Three Phases
Every React component goes through three lifecycle phases. Mounting is when the component is added to the DOM for the first time. Updating is when the component re-renders due to changed props or state. Unmounting is when the component is removed from the DOM. Understanding these phases helps you know when effects run, when to set up and tear down resources, and when to optimize.
useEffect as Lifecycle
In the hooks era, useEffect handles all three phases. An effect with an empty dependency array [] runs once on mount — this replaces componentDidMount. An effect with dependencies [a, b] runs on mount and whenever a or b change — this replaces componentDidUpdate. The cleanup function returned from an effect runs before the next effect and on unmount — this replaces componentWillUnmount. One hook replaces three separate lifecycle methods.
The Mount-Update-Unmount Cycle
When a component mounts, React runs all effects in order. When a dependency changes, React first runs the cleanup of the previous effect, then runs the new effect. When the component unmounts, React runs the final cleanup. This cleanup-before-effect ordering ensures no stale listeners or timers linger. Visualize it as: mount → effect → [deps change → cleanup → effect]* → cleanup → unmount.
From Classes to Hooks
If you are migrating from class components, the mental shift is significant. Instead of thinking "what should I do when the component mounts," think "what do I need to synchronize with these values." The effect runs after render to synchronize the component with some external system (the DOM, a subscription, a timer). The dependency array declares which values the synchronization depends on. This declarative approach is more robust than the imperative lifecycle methods.
Strict Mode Double Invocation
In development, React Strict Mode intentionally double-invokes effects (mount, unmount, mount) to help you find bugs in cleanup logic. This is not a bug — it is a feature. If your effect breaks under double invocation, your cleanup is incomplete. Ensure your cleanup fully reverses the effect so that running the effect twice produces the same result as running it once.
Example
import { useState, useEffect, useRef } from "react";
function LifecycleDemo({ userId }) {
const [data, setData] = useState(null);
const renderCount = useRef(0);
// Track renders — runs after every render (no dependency array).
useEffect(() => {
renderCount.current += 1;
console.log(`Render #${renderCount.current}`);
});
// Mount + update when userId changes — replaces didMount + didUpdate.
useEffect(() => {
console.log(`Fetching data for user ${userId}`);
let cancelled = false;
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(json => { if (!cancelled) setData(json); });
// Cleanup: prevents setting state after unmount or userId change.
return () => { cancelled = true; };
}, [userId]);
// Unmount only — empty deps, cleanup runs on unmount.
useEffect(() => {
console.log("Component mounted");
return () => console.log("Component unmounting");
}, []);
return <div>{data ? data.name : "Loading..."}</div>;
}
Three effects demonstrate the lifecycle: one runs every render, one runs on mount and when userId changes (with cleanup to prevent stale updates), and one logs mount/unmount.
Try it
- Code Diff
Compare class lifecycle methods to their hook equivalents.
- JSON Formatter
Inspect data fetched during the mount/update lifecycle.
Common mistakes
The mistake
Treating useEffect like componentDidMount only
The fix
useEffect is more than a mount hook. Its dependency array controls when it re-runs. Think in terms of synchronizing with values, not lifecycle events. Include all used values in the dependency array.
The mistake
Forgetting cleanup for async operations in effects
The fix
If you fetch data in an effect, use a cancelled flag or AbortController in the cleanup. Without it, the effect may try to update state after the component unmounts, causing warnings or errors.
Practice Component Lifecycle
1 exercise
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.