Skip to content

useEffect: what runs, and in what order

Working knowledgeConceptYou should know: basic React

You log inside a component and inside its useEffect, and the lines come out in an order you did not expect, sometimes twice. Here is the exact sequence React follows: render, commit, cleanup, effect, and what the dependency array decides.

01 Guess the order

A chat room connects when it appears and disconnects when it goes. It logs in three places.

Room.jsx
import { useEffect } from 'react';
export function Room({ roomId }) {
console.log('render', roomId);
useEffect(() => {
console.log('connect', roomId);
return () => console.log('disconnect', roomId);
}, [roomId]);
return <h1>Room {roomId}</h1>;
}

The parent shows Room with roomId="general", switches it to "music", then removes it. Before reading on, write down the six lines you expect in the console.

02 Three phases, always in this order

  • Render: React calls your component. The body runs top to bottom and returns JSX. It must not change anything outside itself, because React may call it at any time, or more than once.
  • Commit: React writes the differences into the DOM. Refs are attached here.
  • Effects: after the commit, and typically after the browser has painted, React runs cleanups and then effects for every component whose dependencies changed.

useEffect does not run your function. It hands the function to React during render, and React decides after the commit whether to call it.

03 One component, from mount to unmount

Mount, change roomId, unmount
Step 1 of 10
deps —
phase
render
commit
paint
cleanup
effect
console
Empty
  • happening now
  • just logged
  • not started

Lobby is about to show Room with roomId="general" for the first time. Nothing has run yet.

general roomId

If Lobby had rendered again with the same roomId, Room would still render and commit, but [general] equals [general], so React would skip both the cleanup and the effect.

04 What the dependency array decides

When the effect runs
You writeEffect runsCleanup runs
useEffect(fn)after every commitbefore each re-run, and on unmount
useEffect(fn, [])once, after mountonce, on unmount
useEffect(fn, [a, b])after mount, and after any commit where a or b changedbefore each re-run, and on unmount

React compares each dependency with its value from the previous render using Object.is. Numbers and strings compare by value; objects, arrays and functions compare by identity, so one created during render is “changed” every time.

Runs after every render
const options = { roomId, retries: 3 };
useEffect(() => {
const c = connect(options);
return () => c.close();
}, [options]);
Runs when roomId changes
useEffect(() => {
const options = { roomId, retries: 3 };
const c = connect(options);
return () => c.close();
}, [roomId]);

05 Parents and children: effects run inside out

Render goes from the top down: a parent is called before its children. Effects go the other way: React runs a child’s effects before its parent’s, so when a parent’s effect runs, every child below it has already set itself up. Within one commit, React runs every cleanup that is due before it runs any new effect.

Mounting a Parent that renders one Child
#What runsPhase
1Parent bodyrender
2Child bodyrender
3DOM updated, refs setcommit
4Child useLayoutEffectlayout effects
5Parent useLayoutEffectlayout effects
6browser paintspaint
7Child useEffecteffects
8Parent useEffecteffects
useLayoutEffectBefore paintRuns right after the DOM changes and blocks the paint. Use it only to measure layout and adjust before the user sees a flicker.
useEffectTypically after paintDoes not hold up the frame. Right for fetching, subscriptions, timers and logging.

“Typically”, because when an update comes from a discrete input such as a click, React 18 and later may run the effects before the browser paints. Your code should not depend on either order.

06 Why it runs twice in development

Under StrictMode, React 18 and later mount every component, run its cleanup, and run the effect again, once, in development only. The console for the room shows:

Text
render general
render general
connect general
disconnect general
connect general

The body runs twice too (React 19 prints both logs; the React DevTools extension greys out the second). This is a check, not a bug: if connect, disconnect, connect leaves the app in the same state as one connect, your cleanup is correct. Production builds run each effect once.

Do not silence the double run with a useRef flag. It hides missing cleanups that will bite later, for example when a user leaves a page and comes back.

07 When effects surprise you

useEffect(() => { setCount(count + 1); });An effect that sets state with no depsSetting state renders, rendering commits, every commit re-runs the effect: an endless loop. Give it dependencies, or compute the value during render.
useEffect(() => { const id = setInterval(() => setN(n + 1), 1000); return () => clearInterval(id); }, []);A missing dependency freezes a valueThe effect only ever sees n from the first render, so the counter sticks at 1. Use the updater form setN(v => v + 1), or list n. The react-hooks/exhaustive-deps lint rule catches this.
useEffect(async () => { ... }, []);An async function as the effectIt returns a promise, not a cleanup, and React warns. Define the async function inside the effect and call it.
fetch(`/rooms/${id}`).then(setRoom)A fetch with no cleanup can raceSwitch rooms quickly and a slow reply for the old room can land last. Set an ignore flag in the cleanup, or abort with an AbortController.

08 Check yourself

Question

roomId changes from a to b. In what order do these happen?

Question

Inside the cleanup that runs during that switch, what is roomId?

Question

A Parent and its Child both log in a useEffect with []. Which logs first on mount?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?