ReactEasy

What is the component lifecycle?

The component lifecycle is the sequence a component goes through: it mounts (appears on screen), updates (re-renders when props, state or context change) and unmounts (is removed). Class components hook into it with lifecycle methods; function components use effects that run after mounting and updating and clean up before re-running or unmounting.

The three phases

  1. Mount: React calls the component, inserts its DOM, then runs effects.
  2. Update: triggered by new props, state changes, context changes or a parent re-render. React re-renders, commits changes, runs cleanups of changed effects, then the effects again.
  3. Unmount: React runs all cleanup functions and removes the DOM.

Function components

  • useEffect(() => { ...; return cleanup }, deps): runs after paint on mount and when deps change; cleanup runs before the next run and on unmount.
  • useLayoutEffect: same timing but before the browser paints.
  • Think in synchronization ("keep this effect in sync with these values") rather than lifecycle events.

Strict Mode in development

React mounts, unmounts and remounts components once to surface missing cleanups. React 19.3 also double-invokes effects during hydration. This does not happen in production.

Related

  • <Activity mode="hidden"> (React 19.2) keeps a component's state while hidden but runs its effect cleanups, and re-runs effects when shown again.
  • Ref callbacks can return cleanup functions in React 19.

Code example

tsx
1import { useEffect, useState } from "react";
2
3function Lifecycle({ userId }: { userId: string }) {
4 console.log("render (mount or update)");
5
6 useEffect(() => {
7 console.log("effect: mounted or userId changed ->", userId);
8 const controller = new AbortController();
9 fetch(`/api/users/${userId}`, { signal: controller.signal }).catch(() => {});
10 return () => {
11 console.log("cleanup: before next effect or on unmount");
12 controller.abort();
13 };
14 }, [userId]);
15
16 return <p>User {userId}</p>;
17}
18
19export function Parent() {
20 const [show, setShow] = useState(true);
21 const [id, setId] = useState("1");
22 return (
23 <>
24 <button onClick={() => setShow((s) => !s)}>{show ? "Unmount" : "Mount"}</button>
25 <button onClick={() => setId((i) => String(Number(i) + 1))}>Next user</button>
26 {show && <Lifecycle userId={id} />}
27 </>
28 );
29}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app