The Analogy: The Window Dresser Who Keeps the Storefront Matched to the Promotion
A department store has a street-facing display window, and one dresser is responsible for keeping it matched to whatever promotion is currently running. The dresser does not touch the window while the floor staff are still rearranging the interior shelves; they wait until the floor is set for the day, then step to the window and dress it to match. The window is an outward-facing thing that must reflect the store's current state, and the dressing always happens after the interior work is finished, never in the middle of it.
Crucially, the dresser does not re-dress the window after every little change inside. They keep a short list of what actually matters: the current promotion. If only the back stockroom was reorganized, the promotion is unchanged, so the window is left exactly as it is. Only when the promotion on that list changes do they redo the window. That list is the whole economy of the job -- it decides when the dresser acts and when they stand down.
Putting up a new display has two halves. First the dresser takes down the previous display -- pulls the old banner, boxes the old props, clears the glass. Only then do they put up the new one. The very first time, on opening week, there is nothing to take down, so they simply set up. And on the day that window is retired, they do the final take-down with no new display to follow. Take-down-before-setup, and a final take-down at the end, keep the glass from ever showing two promotions at once.
The job goes wrong in familiar ways. A dresser working from a photo of the promotion taken on opening day keeps dressing the window to a promotion that ended weeks ago -- they are acting on a stale snapshot. A dresser who forgets to write "promotion" on their list never updates the window at all. One who lists nothing re-dresses the whole window after every trivial shelf nudge, wasting the whole day. And one who forgets the take-down step leaves last month's banner hanging behind this month's, until the glass is a pile of overlapping signage nobody can read.
Syntax or Core Structure
useEffect takes a setup function and, optionally, a dependency array. React runs the setup after the render is committed to the screen; if the setup returns a function, that returned function is the cleanup, run before the next setup and at unmount. The dependency array is the dresser's list: it decides when the setup re-runs.
import { useState, useEffect } from "react";
function TitleCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = "You clicked " + count + " times";
}, [count]); // re-dress the window only when count changes
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
That effect touches the real document title, so it has no traceable return value. To see the decision logic deterministically, model what React does across a run of renders: compare this render's deps to the previous render's, and log setup, skip, or cleanup accordingly.
function sameDeps(a, b) {
if (a === null || b === null) return false;
return a.length === b.length && a.every((v, i) => v === b[i]);
}
const renders = [{ count: 0 }, { count: 0 }, { count: 1 }];
let prevDeps = null;
const log = [];
renders.forEach((r, i) => {
const deps = [r.count];
if (!sameDeps(prevDeps, deps)) {
if (prevDeps !== null) log.push("render " + i + ": cleanup");
log.push("render " + i + ": run effect (count=" + r.count + ")");
prevDeps = deps;
} else {
log.push("render " + i + ": skip");
}
});
console.log(log.join("\n"));
Output:
render 0: run effect (count=0)
render 1: skip
render 2: cleanup
render 2: run effect (count=1)
Render 0 is the mount -- setup with nothing to clean up first. Render 1 has identical deps, so the effect is skipped entirely. Render 2 changed count, so React cleans up the previous setup and runs a fresh one, exactly like taking down the old display before putting up the new.
Technical Depth: The Dependency List and Cleanup
The second argument is a decision table
The dependency array is the entire contract for when an effect fires. There are three cases, and choosing the wrong one is the source of most effect bugs.
| Second argument | Setup runs | Cleanup runs |
|---|---|---|
| omitted | after every render | before each re-run, and at unmount |
[] | once, after mount | only at unmount |
[a, b] | after mount, then when a or b changes | before each re-run, and at unmount |
Cleanup keeps setups from piling up
Every setup should have a matching cleanup. Model a subscription as a counter that setup increments and cleanup decrements: with cleanup the active count holds at one, and without it the count climbs on every re-run -- exactly the leaked-interval bug.
function simulate(withCleanup) {
let active = 0;
const log = [];
const setup = () => { active++; };
const cleanup = () => { active--; };
for (let i = 0; i < 3; i++) {
if (i > 0 && withCleanup) cleanup();
setup();
log.push("after render " + i + ": active=" + active);
}
return log.join("\n");
}
console.log("with cleanup:");
console.log(simulate(true));
console.log("without cleanup:");
console.log(simulate(false));
Output:
with cleanup:
after render 0: active=1
after render 1: active=1
after render 2: active=1
without cleanup:
after render 0: active=1
after render 1: active=2
after render 2: active=3
Object dependencies change identity every render
Dependencies are compared by identity (Object.is). An object or array literal written inline is a new value each render, so an effect that depends on it re-runs every single time -- and if the effect also sets state, that is an infinite loop.
const r0 = { v: 1 };
const r1 = { v: 1 };
console.log("Object.is:", Object.is(r0, r1));
Output:
Object.is: false
Racing replies, and ignoring the stale one
When an effect fetches on a changing input, replies can arrive out of order: a slow reply for an old input can land after the reply for the current one and overwrite it. The cleanup function is where you neutralize the old request -- set an ignore flag so a stale reply is dropped. Model two replies arriving in the wrong order.
function resolveOrder(withGuard) {
const events = [];
const current = "ab";
const replies = { a: "results for a", ab: "results for ab" };
const arrival = ["ab", "a"]; // the slow "a" reply lands last
let shown = "(none)";
arrival.forEach((q) => {
const stale = q !== current;
if (withGuard && stale) {
events.push("ignore stale reply: " + q);
} else {
shown = replies[q];
events.push("show: " + replies[q]);
}
});
events.push("final -> " + shown);
return events.join("\n");
}
console.log("without guard:");
console.log(resolveOrder(false));
console.log("with guard:");
console.log(resolveOrder(true));
Output:
without guard:
show: results for ab
show: results for a
final -> results for a
with guard:
show: results for ab
ignore stale reply: a
final -> results for ab
Effects run in declaration order, after commit
Within one render React computes the view, commits it to the screen, and only then runs the effects -- and multiple effects run top to bottom in the order they are written.
const order = [];
const effects = [
() => order.push("effect A: sync title"),
() => order.push("effect B: sync subscription"),
];
effects.forEach((fn) => fn());
console.log(order.join("\n"));
Output:
effect A: sync title
effect B: sync subscription
The full mount-update-unmount timeline
Putting the pieces together, an effect with deps [id] sets up at mount, cleans up and re-sets up when id changes, skips when it does not, and cleans up one last time at unmount. This trace walks a component through mount, a no-op render, an id change, and unmount.
function lifecycle(ids) {
const log = [];
let mounted = false;
let prev = null;
ids.forEach((id) => {
if (mounted && id !== prev) log.push("cleanup(id=" + prev + ")");
if (!mounted || id !== prev) {
log.push("setup(id=" + id + ")");
prev = id;
mounted = true;
}
});
log.push("cleanup(id=" + prev + ") // unmount");
return log.join("\n");
}
console.log(lifecycle([7, 7, 9]));
Output:
setup(id=7)
cleanup(id=7)
setup(id=9)
cleanup(id=9) // unmount
Read top to bottom, the trace is the dresser's whole week: open the window, leave it alone when nothing relevant changed, take it down and redo it when the promotion changed, and take it down for good at the end. Every setup is balanced by exactly one cleanup, which is the invariant a correct effect must preserve.
Real World Example: A Poller That Logs the Same Count Forever
A common feature: on mount, start an interval that periodically reports the current count. The obvious implementation uses an empty dependency array so the interval is set up once. Modeled deterministically, here is what the interval actually reports as count climbs across renders.
// With deps [], the effect runs once at mount and its callback closes over
// count = 0. Later renders change count but never re-run the effect, so the
// captured value never moves. Model the reports the interval would emit.
function tickLog(capturedCount, ticks) {
const out = [];
for (let i = 1; i <= ticks; i++) {
out.push("tick " + i + ": count = " + capturedCount);
}
return out.join("\n");
}
// The real count advanced 0 -> 1 -> 2 -> 3 across renders,
// but the mount-time effect captured it once at 0.
console.log("empty deps [] (stale):");
console.log(tickLog(0, 3));
// Fix: list count in deps, so each render re-runs the effect with a fresh
// closure. One captured value per render.
const capturedPerRender = [0, 1, 2, 3];
const fixed = [];
for (let i = 1; i <= 3; i++) {
fixed.push("tick " + i + ": count = " + capturedPerRender[i]);
}
console.log("deps [count] (fresh):");
console.log(fixed.join("\n"));
Output:
empty deps [] (stale):
tick 1: count = 0
tick 2: count = 0
tick 3: count = 0
deps [count] (fresh):
tick 1: count = 1
tick 2: count = 2
tick 3: count = 3
At a glance the empty-array version looks like a textbook "run once on mount" effect, and for a timer that ignores state it would be correct. The interval is created a single time, no needless teardown churns the timer, and the setup reads count right there in the closure -- everything appears wired up. The bug never shows until the reported value is supposed to track state.
The reason it fails is the dresser working from an opening-day photo. The empty dependency array tells React never to re-run the effect, so the callback keeps the exact count binding it captured at mount, which was 0. Every tick faithfully reports that frozen value while the real state marches 1, 2, 3. The output's first block is three identical zeros -- the smoking gun of a stale closure.
That is the real design flaw: the dependency array is dishonest. It claims the effect depends on nothing, when the effect plainly reads count. Listing count in the deps (the second block) makes each render tear down the old interval and set up a fresh closure, so the reports track state. But that fix has its own cost worth naming: recreating the interval on every change resets its timer, so for a steady clock the better shape is a functional updater or a ref that lets one long-lived interval read the latest value without re-subscribing.
Common Mistakes
- Omitting the dependency array by accident. With no second argument the effect runs after every render; if it fetches or subscribes, it does so on every render.
- Empty deps while reading changing state.
[]freezes the setup's closure at mount, so it keeps reading the mount-time value -- the stale-closure bug.
- Forgetting the cleanup. Every listener, interval, or subscription set up must be torn down in the returned function, or they pile up on each re-run and at unmount.
- Lying about dependencies. Leaving a value the effect uses out of the array to "stop it re-running" trades a re-render for a stale bug; fix the code, not the list.
- Inline object or function dependencies.
[{ id }]or[() => {}]is a new value every render, so the effect never gets to skip.
- Setting state unconditionally inside the effect. If the effect sets a value that is also in its deps, each run schedules another run -- an infinite loop.
- Using an effect for event logic. "When the user clicks, do X" belongs in the click handler, not in an effect that watches a flag.
- Deriving data through an effect. Computing a value into state inside an effect adds a render and can drift; derive it during render instead.
- Passing an async function as the effect.
useEffect(async () => ...)returns a Promise where React expects a cleanup or nothing; define an async function inside and call it.
Best Practices
- Treat an effect as synchronization. Ask "what external system am I keeping in sync with this state?" -- not "what should happen at this lifecycle moment?"
- List every reactive value the effect reads. Trust the exhaustive-deps lint; a complete list is what keeps the effect honest.
- Always return a cleanup for anything you start. Listener, interval, socket, subscription -- each setup gets a matching teardown.
- Reach for a functional updater or a ref to read latest state. It avoids re-subscribing just to see the current value, keeping long-lived setups stable.
- Keep each effect to one concern. Two unrelated synchronizations are two effects, so their dependencies and cleanups do not entangle.
- Stabilize object and function dependencies. Hoist constants out of render or memoize them so the deps can actually match between renders.
- Do not use effects for derivable data or event responses. Compute during render, or handle it in the event, and the effect disappears.
- Cancel stale work in the cleanup. For fetches, ignore or abort a response whose effect has already been cleaned up, so a slow reply cannot overwrite newer state.
Practice Exercises
- Run the effect scheduler by hand for five renders whose deps are
[0], [0], [1], [1], [2], and write the run / skip / cleanup line each render produces.
- Take
simulate(false)from the cleanup example and add a cleanup call so the active count stays at 1 across all three renders; confirm the new output.
- Explain in one sentence why the poller logs
count = 0forever withdeps = [], then give two distinct fixes and state the timer-reset cost of the deps-based one.
- Given
useEffect(() => {}, [{ id: 1 }]), explain why it runs after every render, and rewrite the dependency so the effect can skip when nothing meaningful changed.