Question presented to candidate:
"What is the function you return from useEffect for, and exactly when does React call it?"
What a strong answer should cover:
- It undoes what the effect set up — unsubscribe, clear a timer, abort a request, disconnect an observer.
- The timing, stated precisely: it runs before the next effect run (when a dependency changed) and again on unmount. Never after the next run.
- Each cleanup closes over the values from its own run, which is what makes it able to tear down the right thing.
- Every setup has exactly one teardown — the counts always balance.
- Why it matters: without it, each re-run leaks the previous subscription, and they accumulate.
- Return nothing if there is nothing to undo — do not return a value, and never make the effect callback
async, because that returns a promise where React expects a function. StrictModedeliberately mounts, cleans up, and remounts in development so a missing cleanup fails immediately.- The cancellation-flag pattern for fetches is cleanup used to guard against a stale response, not just to free a resource.
Clarifying questions expected:
- "Is the effect setting up something that persists — a listener, a timer, a request?" If not, it may not need cleanup at all.
Code / implementation expected: Yes — a subscription effect whose cleanup is visibly balanced against its setup.