React Component Lifecycle: Mount, Update and Unmount with Examples
Trace one component from its first render to cleanup. The example shows which state survives an update, when an Effect reconnects, and what resets after remounting.
KnowledgeGate Team
Exam prep & CS education

A component can display the right JSX while a subscription remains attached to the wrong prop. Cleanup may appear during an update, and development logs may look as if the component mounted twice. The useful mental model separates render, commit, mount, update, unmount, and an Effect's setup-cleanup cycle. If you are building the wider foundation around this topic, browse Coding & Skills alongside this walkthrough.
React component lifecycle starts with mount, update and unmount
A component mounts when it is added to the screen, updates when new props or state produce another render, and unmounts when it is removed. Suppose StatusBadge({ active }) mounts with active = false. It displays Offline. Updating the prop to true displays Online. When the parent changes showBadge from true to false, the badge disappears and that component instance ends.
Rendering calculates the next JSX from current props and state. Committing applies the accepted result to the DOM. Render logic must stay pure. An Effect synchronises an external system after a commit; it should not calculate active ? "Online" : "Offline".
Function components and class lifecycle methods use different models
Classes organise side effects around component lifecycle methods. Function components express each external synchronisation as an Effect with its own setup and cleanup.
Moment | Class component | Function component Effect |
|---|---|---|
Initial commit |
| The Effect can run setup |
Later commit with changed |
| Cleanup uses the old value, then setup uses the new value |
Removal |
| The Effect runs its final cleanup |
Render |
| The component function calculates UI; neither cleanup path belongs here |
useEffect(() => {
const disconnect = connect(roomId);
return disconnect;
}, [roomId]);The component has a mount-update-unmount lifetime, but this Effect has a repeatable start-stop cycle. useEffect is not a one-for-one replacement for every class lifecycle method. For the broader relationship among useState, useEffect, useMemo and custom hooks, read React Hooks: useState, useEffect & useMemo Explained. Component lifecycle focuses instead on instance identity, state persistence and cleanup order.
Runnable worked example: trace one room through its full lifecycle
Put this exact example in App.jsx. The connection is represented by console messages, while notes lets us see which local state survives.
import { useEffect, useState } from "react";
function connect(roomId) {
console.log(`connect:${roomId}`);
return () => console.log(`disconnect:${roomId}`);
}
function RoomPanel({ roomId }) {
const [notes, setNotes] = useState(0);
useEffect(() => {
return connect(roomId);
}, [roomId]);
return (
<section>
<p>Room {roomId}: {notes} notes</p>
<button onClick={() => setNotes(n => n + 1)}>Add note</button>
</section>
);
}
export default function App() {
const [roomId, setRoomId] = useState(101);
const [show, setShow] = useState(true);
return (
<main>
<button onClick={() => setRoomId(id => id === 101 ? 202 : 101)}>
Switch room
</button>
<button onClick={() => setShow(value => !value)}>
{show ? "Hide" : "Show"} panel
</button>
{show && <RoomPanel roomId={roomId} />}
</main>
);
}For the initial non-Strict-Mode trace, the first committed UI is Room 101: 0 notes. The Effect then logs connect:101. Click Add note once. The updater receives 0, returns 0 + 1 = 1, and the committed UI becomes Room 101: 1 notes. roomId is still 101, so the Effect dependency has not changed. There is no disconnect or reconnect.
Do not add key={roomId} to RoomPanel here. A changing key would replace the component instance when the room changes instead of demonstrating an ordinary prop-driven update. Replacement would also reset local notes state to 0, hiding the important contrast between an update and a genuine unmount followed by a remount.
Follow the exact cleanup order on update, unmount and remount
Continue from Room 101: 1 notes. Clicking Switch room commits Room 202: 1 notes. The old Effect then logs disconnect:101, followed by the new setup log connect:202. Cleanup ran even though RoomPanel did not unmount, because its dependency changed from 101 to 202.
Clicking Hide panel removes RoomPanel and logs disconnect:202. Clicking Show panel creates a new instance. Its state starts at 0, the UI commits Room 202: 0 notes, and setup logs connect:202. Thus notes = 1 survived the prop update, but the real unmount and remount reset it to 0. After cleanup and setup settle, at most one connection matching the committed roomId should remain active.

Development checks can rehearse setup and cleanup
When a Strict Mode development check is active, the initial roomId = 101 Effect trace can be connect:101, disconnect:101, connect:101. This extra setup-cleanup-setup rehearsal checks whether cleanup fully mirrors setup. It does not justify promising that every environment, build, or future React version will print an identical number of render logs.
Keep the cleanup, and make connect(101) safe after disconnect(101). Do not hide the second setup behind a ref flag or disable development checks merely to silence the console. Also separate component function calls from Effect logs. Render must remain pure even if React evaluates it more than once. Network connections, timers, and event listeners belong in an Effect with matching cleanup.

Common lifecycle errors and the smallest correct fix
Problem | Consequence | Smallest correct fix |
|---|---|---|
Missing | The UI changes from | Include |
Missing cleanup | Hiding the panel leaves the | Return the exact disconnect function created by that setup |
| Hook order becomes unstable | Keep the Hook at the top level and conditionally render |
An update loop is another common error:
useEffect(() => setNotes(notes + 1), [notes]);It changes 0 to 1, then 1 to 2, and keeps scheduling updates because every new notes value retriggers the Effect. Move the increment into the Add note click handler, because the click is the cause. Derived display text also belongs in render:
const label = notes === 1 ? "1 note" : `${notes} notes`;Most external synchronisation belongs in useEffect. Reach for useLayoutEffect only when a visual measurement must happen before paint and layout blocking is actually necessary.
Assessment patterns and exact practice exercises
Starting at
101, mount, clickAdd noteonce, switch to202, then hide. The non-Strict-Mode logs areconnect:101, no connection log for the note update,disconnect:101,connect:202,disconnect:202. The visible note count remains1until hide.Add
pollMs, initially5000, and use[roomId, pollMs]. Changing onlypollMsto2000must clean up the101/5000poller before starting101/2000. Switching room then replaces it with202/2000.Convert the connection to a class. Connect
101incomponentDidMount, compare previous and currentroomIdincomponentDidUpdate, then disconnect the current202incomponentWillUnmount.
Use the first trace to test cleanup order, the poller variant to test multiple dependencies, and the class conversion to test lifecycle-method mapping.
The short version and the next study step
Render calculates UI. Mount, update, and unmount describe the component. Each Effect starts and stops one external synchronisation, and changed dependencies require old cleanup before new setup. In 101 -> 202 -> hidden -> shown, state survives the room update but resets after remounting. Continue with the catalog's React and Redux course, or take the project-focused route through the MERN Stack course.
Keep learning
React Component Lifecycle Interview Questions and Coding Problems: Trace Every Phase
Learn one render, commit, setup, and cleanup model. Then use it to solve exact class lifecycle traces and two common React coding-round problems.
How the MERN Stack Fits Together: One Request Traced from a React Click to MongoDB and Back
Follow one Enroll action through React, HTTP, Express, Mongoose, and MongoDB, then trace the JSON response back to the browser and its updated state.
Testing React Components: A Runnable Vitest and Testing Library Tutorial
Build and test a small React progress component from its initial render through completion. The examples use accessible queries, awaited actions, and an exact mock assertion.
React Performance Optimization Tutorial: Profiler, memo, useMemo, and useCallback Examples
Build one React lab, measure its render and calculation counts, then remove avoidable work while keeping typing responsive.





