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

Updated 1 Dec 20266 min read
React Component Lifecycle: Mount, Update and Unmount with Examples

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

componentDidMount can start work

The Effect can run setup

Later commit with changed roomId

componentDidUpdate(prevProps) must compare values

Cleanup uses the old value, then setup uses the new value

Removal

componentWillUnmount performs cleanup

The Effect runs its final cleanup

Render

render() calculates UI

The component function calculates UI; neither cleanup path belongs here

jsx
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.

jsx
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.

Eleven-step RoomPanel timeline: notes persist when room 101 updates to 202, then reset to zero after hiding and remounting the panel.

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.

Console timelines compare one production connection with a development connect-disconnect-connect rehearsal; both finish with one active room 101 connection.

Common lifecycle errors and the smallest correct fix

Problem

Consequence

Smallest correct fix

Missing [roomId]

The UI changes from 101 to 202, but the Effect stays connected to 101

Include roomId in the dependency list

Missing cleanup

Hiding the panel leaves the 202 resource active

Return the exact disconnect function created by that setup

if (show) useEffect(...)

Hook order becomes unstable

Keep the Hook at the top level and conditionally render RoomPanel in the parent

An update loop is another common error:

jsx
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:

jsx
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

  1. Starting at 101, mount, click Add note once, switch to 202, then hide. The non-Strict-Mode logs are connect:101, no connection log for the note update, disconnect:101, connect:202, disconnect:202. The visible note count remains 1 until hide.

  2. Add pollMs, initially 5000, and use [roomId, pollMs]. Changing only pollMs to 2000 must clean up the 101/5000 poller before starting 101/2000. Switching room then replaces it with 202/2000.

  3. Convert the connection to a class. Connect 101 in componentDidMount, compare previous and current roomId in componentDidUpdate, then disconnect the current 202 in componentWillUnmount.

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.