Effects from scratch

Run code after commit, clean it up, and map the toy to real React.

Builds on Hooks from scratch.

The toy can now render, diff, pause, and remember state. Everything it does is pure: components take props and state and return elements. Real apps also have to reach outside: set the page title, start a timer, subscribe to a WebSocket, measure a DOM node, fetch data. Chapter 7 made a hard rule that this can't happen during render, because a render can run twice, be paused, or never be committed.

So where does it go? After the commit, when the screen really shows what the component rendered. This chapter adds useEffect to the toy, which completes it, and then maps every piece of the toy to the real React it imitates, naming the places where React is more sophisticated.

The problem: side effects in render#

Here's a clock on the stage 8 toy. It starts its timer in the component body, which feels natural: "when this component exists, tick every second". The console counts how many intervals are running.

A clock that speeds up
import { createElement, render, useState } from "./toy.js";

let running = 0;

function Clock() {
  const [seconds, setSeconds] = useState(0);

  // A side effect during render: runs on every render, never stopped.
  // (Capped at 32 intervals so this demo can't freeze your tab.)
  if (running < 32) {
    running++;
    setInterval(() => setSeconds((s) => s + 1), 1000);
    console.log(`render: ${running} intervals running`);
  }

  return <p>Seconds: {seconds}</p>;
}

render(<Clock />, document.getElementById("root"));
Nothing logged yet.

Every tick re-renders, every render starts another interval, and the clock accelerates, the number of intervals roughly doubling every second. (The demo stops adding intervals at 32; without that cap it would keep doubling until the tab froze.) Two things are missing. The effect should run after a render is committed, and only when something it depends on changed. And it needs a way to undo itself: stop the old interval before starting a new one, and stop it for good when the component goes away.

Build it: useEffect#

Record during render, run after commit#

useEffect(create, deps) doesn't run anything when it's called. It stores a hook in the next slot, exactly like useState does, and decides whether this effect needs to run:

export function useEffect(create, deps) {
  const oldHook = wipFiber.alternate?.hooks?.[hookIndex];
  const changed =
    !oldHook || !deps || !oldHook.deps || deps.length !== oldHook.deps.length || deps.some((dep, i) => !Object.is(dep, oldHook.deps[i]));
  const hook = {
    deps,
    create,
    hasChanged: changed,
    inst: oldHook ? oldHook.inst : { destroy: undefined }, // holds the cleanup
  };
  wipFiber.hooks.push(hook);
  hookIndex++;
}

The dependency rules come straight from that changed line:

  • First render (no old hook): run.
  • No dependency array: run after every render.
  • An array: run only if some dependency differs from last time by Object.is. An empty array [] never differs, so the effect runs once, after mount.

inst is a small object shared by every render's version of this hook, holding the cleanup function the effect returned last time. React 19 uses the same trick, with the same name.

Collect at commit, children first#

After the commit has applied the DOM changes, commitRoot collects the effects that need to run:

// Children before parents: a parent's effect can rely on its children's.
function collectEffects(fiber) {
  for (let child = fiber.child; child; child = child.sibling) collectEffects(child);
  for (const hook of fiber.hooks ?? []) if (hook.inst && hook.hasChanged) pendingEffects.push(hook);
}

It's a post-order walk, children before their parent, the same order in which fibers complete. By the time a parent's effect runs, its children's DOM is in place and their effects have run. (Only effect hooks have inst, which is how collectEffects skips useState slots.)

Run later: all cleanups, then all effects#

The effects don't run inside commitRoot. They're scheduled for a later task, so the browser can paint the new screen first:

export function flushPassiveEffects() {
  effectsScheduled = false;
  const unmounts = pendingUnmounts;
  const effects = pendingEffects;
  pendingUnmounts = [];
  pendingEffects = [];
  // 1. Every cleanup first: removed components, then effects about to re-run.
  unmounts.forEach(runCleanup);
  effects.forEach((hook) => runCleanup(hook.inst));
  // 2. Then every effect, with its cleanup saved for next time.
  for (const hook of effects) {
    const destroy = hook.create();
    hook.inst.destroy = typeof destroy === "function" ? destroy : undefined;
  }
}

Two details matter:

  • Every cleanup runs before any new effect. If effect A's cleanup unsubscribes from a store and effect B subscribes to it, the old subscriptions are all gone before new ones start, so nothing sees a mix of old and new.
  • The cleanup is the one from the previous run, a closure over the previous render's values. When roomId changes from "general" to "music", the cleanup disconnects from "general", which is exactly right.

Removed components are handled in commitDeletion: their whole subtree's effect instances go into pendingUnmounts, so their cleanups run at the next flush too.

Finally, prepareNextRoot calls flushPassiveEffects() before it starts a new render, so effects from one commit always run before the next render begins, even if the scheduled task hasn't fired yet. React does the same.

When effects run
rendercommitpaintpassive effectsmountrenderApp, Child runcommitinsert DOMpaintpassive effectsn: 0 → 1rendercommitpaintpassive effectsunmountrendercommitpaintpassive effectsPassive effects run in a later task, or just before the next render starts.
Step 1 of 6

Mount. The render phase calls App and Child; useEffect only records the effect. The commit inserts the DOM. Layout effects (useLayoutEffect) would run here, before the browser paints.

Here's the stage 9 toy with a fixed clock (an interval created in an effect, cleared in its cleanup), plus a component that logs its effects so you can watch the order. Press the buttons and read the console.

useEffect on the toy
import { createElement, render, useState, useEffect } from "./toy.js";

function Clock() {
  const [seconds, setSeconds] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setSeconds((s) => s + 1), 1000);
    return () => clearInterval(id);
  }, []);
  return <p>Clock: {seconds}s</p>;
}

function Room({ roomId }) {
  useEffect(() => {
    console.log(`connect to ${roomId}`);
    return () => console.log(`disconnect from ${roomId}`);
  }, [roomId]);
  return <p>Room: {roomId}</p>;
}

function App() {
  const [roomId, setRoomId] = useState("general");
  const [show, setShow] = useState(true);
  useEffect(() => {
    console.log("App effect (runs after its children's)");
  }, []);
  return (
    <div>
      <Clock />
      <button onClick={() => setRoomId(roomId === "general" ? "music" : "general")}>Switch room</button>{" "}
      <button onClick={() => setShow(!show)}>{show ? "Leave" : "Join"}</button>
      {show ? <Room roomId={roomId} /> : null}
    </div>
  );
}

render(<App />, document.getElementById("root"));
Nothing logged yet.

On mount, connect to general is logged before App effect: children first. Switch room logs the disconnect from the old room, then the connect to the new one. Leave logs one disconnect and nothing else. The clock ticks once a second no matter how often the rest re-renders, because its effect has [] dependencies and a cleanup.

Fix itThe ticker that never stops

Ticker counts up to 100, one tick every 20 ms. It has two bugs: intervals pile up while it's mounted (watch how fast it reaches 100), and they keep running after it's removed. Fix ticker.js. Press Check when you think it works.

import { createElement, useState, useEffect } from "./toy.js";

export function Ticker({ onTick }) {
  const [n, setN] = useState(0);
  useEffect(() => {
    setInterval(() => {
      onTick?.();
      setN((x) => Math.min(x + 1, 100)); // stops re-rendering at 100
    }, 20);
  });
  return <p>Ticks: {n}</p>;
}

The real thing: effects in React#

React's useEffect works like the toy's: recorded during render, compared by Object.is dependency by dependency, run after commit with all cleanups before all new effects, children before parents, and cleaned up on unmount. Some details are different or extra.

Timing. Passive effects normally run after the browser paints, flushed by a scheduled task, or earlier if another render is about to start. One nuance, straight from the docs: if your effect was caused by an interaction like a click, React may run it before the browser paints the updated screen, so the event system can observe its result. Don't rely on effects running before or after paint; if you must block painting, use the next hook.

useLayoutEffect runs synchronously during the commit, after the DOM has been mutated and before the browser paints. It's for reading layout (a tooltip measuring its size) and synchronously re-rendering before the user sees anything. It blocks painting, so keep it for that. useInsertionEffect runs even earlier, before layout effects, and exists for CSS-in-JS libraries to inject style tags.

Strict Mode in development mounts every component, runs its effects, simulates an unmount (running cleanups), and mounts again. If your cleanup doesn't fully undo the effect, the double mount makes the bug visible immediately, a duplicate subscription or a second interval, instead of on some later navigation. React 19.3 React 19.3 also does this for components that hydrate from server HTML. Effects covers why, and what a correct cleanup looks like.

Storage. Each effect is an object { tag, create, deps, inst: { destroy }, next }. The hook's memoizedState points to it, and the fiber's updateQueue keeps all of the component's effects in a circular list (lastEffect), with flags saying which ones must fire. The commit phase uses fiber flags (Passive) and subtreeFlags to find components with pending effects without visiting the whole tree.

Watch the real order, with Strict Mode on:

Effect order in React, with Strict Mode
import { useEffect, useLayoutEffect, useState } from "react";

function Child({ n }) {
  console.log(`render Child(n=${n})`);
  useLayoutEffect(() => {
    console.log(`  layout effect, n=${n}`);
    return () => console.log(`  layout cleanup, n=${n}`);
  }, [n]);
  useEffect(() => {
    console.log(`  effect, n=${n}`);
    return () => console.log(`  cleanup, n=${n}`);
  }, [n]);
  return <p>n = {n}</p>;
}

export default function App() {
  const [n, setN] = useState(0);
  const [show, setShow] = useState(true);
  return (
    <div>
      <button onClick={() => setN(n + 1)}>n + 1</button>{" "}
      <button onClick={() => setShow(!show)}>{show ? "Unmount" : "Mount"} Child</button>
      {show && <Child n={n} />}
    </div>
  );
}
Nothing logged yet.

On mount you'll see Child render twice and its effects run, clean up, and run again: that's Strict Mode checking your cleanups. Then n + 1 shows the layout cleanup and layout effect (during the commit) before the passive cleanup and effect, and Unmount runs both cleanups. Turn off Strict Mode in your head and each of those happens once.

React 19.2 When an effect needs the latest value of a prop or state without re-running when it changes, React 19.2 added useEffectEvent. It's covered with the real effects chapter, along with the most important effect skill of all: noticing when you don't need one.

The whole toy, mapped to React#

You've built every core idea of React's runtime in about 500 lines. Here's every piece, what it's called in React, and where React does more.

Toy (stage)React APIReact internalsWhere React differs
createElement, Fragment (3)JSX, jsx() from react/jsx-runtime, createElement, <Fragment>Element object { $$typeof, type, key, props }Text children stay strings; children aren't flattened; Fragment is a special symbol type, not a component; $$typeof guards against injected objects; elements are frozen in development.
render, createRoot (4, 7)createRoot(container).render(el)A FiberRoot with a HostRoot fiber; updateContainer schedules the updateRendering is scheduled with a priority lane; root.unmount(); hydrateRoot for server HTML.
createDom, updateDom (4)(react-dom)The DOM host config: createInstance, commitUpdate, setInitialPropertiesHundreds of attribute and property special cases, px for numeric styles, controlled inputs, custom elements.
One listener per node per event (4)onClick and friendslistenToAllSupportedEvents on the root container; synthetic events dispatched through the fiber treeOne listener per event type at the root; event priority decides update priority.
reconcile, patches (5)ReconciliationreconcileChildFibers; changes recorded as flags, not a patch listCan skip unchanged subtrees (bailoutOnAlreadyFinishedWork); empty children keep their positions.
Keyed reconcileChildren, lastPlacedIndex (6, 7)keyreconcileChildrenArray, mapRemainingChildren, placeChildA fast path that walks old and new children together while keys match, before building a map.
Fiber { type, props, dom, child, sibling, return, index, alternate, flags } (7)(internal)FiberNode: tag, stateNode, pendingProps, memoizedProps, memoizedState, updateQueue, flags, subtreeFlags, lanes, childLanesMany fiber kinds (tag): class, host, text, Suspense, Activity, context, memo and more.
createWorkInProgress, alternate, __rootFiber (7)(internal)createWorkInProgress, alternate, root.currentSame double buffering. React also reuses bailed-out subtrees as they are.
workLoop, shouldYield, MessageChannel, 5 ms slices (7)Concurrent renderingworkLoopSync, workLoopConcurrentByScheduler, the scheduler package (frameInterval 5 ms)Only non-blocking lanes (transitions, retries, offscreen) are sliced; a render can be interrupted, discarded and restarted.
performUnitOfWork, beginWork, completeWork (7)(internal)Same names, plus completeUnitOfWorkcompleteWork also handles context, Suspense boundaries and host-specific work.
Placement, Update, global deletions (7)(internal)Placement, Update, ChildDeletion flags; fiber.deletions on the parent; subtreeFlagsDeletions live on the parent fiber; subtreeFlags lets the commit skip clean subtrees.
commitRoot, commitWork, getHostSibling (7)The commit phasecommitRoot: before-mutation, mutation (commitMutationEffectsOnFiber), layout (commitLayoutEffectOnFiber)Refs attached, layout effects and class lifecycles run during commit; View Transitions hook in here.
rootQueue, scheduleWork batching (7, 8)Automatic batchingscheduleUpdateOnFiber, ensureRootIsScheduled, lanes (SyncLane, DefaultLane, TransitionLanes, ...)Updates carry priorities; urgent work can interrupt a transition. Batching works the same: one render per task.
wipFiber, hookIndex, fiber.hooks (8)Rules of HookscurrentlyRenderingFiber, currentHook and workInProgressHook walking a linked list on memoizedState; dispatcher ReactSharedInternals.HA linked list instead of an array; separate mount and update dispatchers; errors when the hook count changes.
useState, queue, dispatch, Object.is bailout (8)useStatemountState, updateState (built on useReducer), dispatchSetState, a circular queue of updates with lanes, eager stateUpdates are processed by priority, with baseState/baseQueue keeping skipped ones; may render and then bail out.
useEffect, inst.destroy, collectEffects, flushPassiveEffects (9)useEffectEffect objects { tag, create, deps, inst, next } in updateQueue.lastEffect; Passive flags; flushPassiveEffectsuseLayoutEffect and useInsertionEffect; Strict Mode double invocation; effects from discrete events may flush before paint.
act (7, 9)act from reactFlushes scheduled work and effectsAlso waits for async work and Suspense in tests.

What the toy never built, and where you'll meet it: context (chapter 16), refs (chapter 14), memo and the Compiler (chapters 29 and 30), error boundaries (chapter 21), and Suspense and transitions (chapters 24 and 26). Each of them is a new kind of fiber, a new flag or a new lane on the same machinery you just built. Server rendering is the exception: React's server renderer is a separate implementation that streams HTML without fibers, and the client then hydrates it (chapter 43).

Pitfalls#

Check your understanding#

PredictWhat logs, in what order?

In real React without Strict Mode, Parent renders Child once, then re-renders with id changed from 1 to 2. What's logged across both renders?

function Child({ id }) {
  useEffect(() => {
    console.log("child effect", id);
    return () => console.log("child cleanup", id);
  }, [id]);
  return null;
}

function Parent({ id }) {
  useEffect(() => {
    console.log("parent effect", id);
    return () => console.log("parent cleanup", id);
  }, [id]);
  return <Child id={id} />;
}
Quick checkDependency arrays

An effect is declared as useEffect(fn, []). When does fn run?

Explain it out loudHow does useEffect work?

An interviewer asks: "When does a useEffect callback run, and how does React decide whether to run it again?"

Interview angle

Say it in 30 seconds

Rendering must be pure because a render can run twice, pause or never commit, so side effects go in useEffect. During render, useEffect only stores the callback and its dependencies on the fiber and compares each dependency with Object.is. After the commit, React runs the effects whose dependencies changed, usually after paint: first every relevant cleanup from the previous run, then every new effect, children before parents. Unmounting runs the cleanups one last time. useLayoutEffect runs synchronously during commit, before paint, for measuring layout. Strict Mode mounts, cleans up and remounts in development to expose missing cleanups.

When does a useEffect callback run?

basic

How does the dependency array work?

basic

In what order do cleanups and effects run when dependencies change?

intermediate

useEffect doesn't run anything when you call it. So where does the effect go, and how does React find it after the commit?

senior

Why are effects flushed in a separate task after the commit instead of right after the DOM is updated?

intermediate

If you've built a toy React, what are the main things real React adds?

senior

Recap#

  • Side effects can't run during render, because a render may run twice, pause or never commit. useEffect records a function during render and runs it after the commit.
  • Dependencies are compared with Object.is, one by one. No array: every render. []: once after mount. Otherwise: when something changed.
  • After a commit, React runs all pending cleanups, then all new effects, children before parents, usually after paint. Unmounting runs the cleanups one last time.
  • useLayoutEffect runs synchronously during the commit, before paint. Strict Mode mounts, cleans up and remounts in development to expose missing cleanups.
  • The toy maps one to one onto React's runtime: elements, fibers with child/sibling/return/alternate, a work loop with render and commit phases, hooks on the fiber in call order, and effects flushed after commit. React adds lanes, bailouts, interruption and many more fiber kinds.

Sources#