Effects, cleanup, and async races
Prevent stale requests and abandoned subscriptions from changing the current screen while keeping derived work out of Effects.
What you will be able to do
- Distinguish rendering, user events and external synchronization.
- Model request identity separately from completion order.
- Implement cleanup and explain why cancellation alone is not a complete consistency rule.
Before this lesson
An Effect owns a synchronization process
A catalogue result can be calculated from existing items and a search term during rendering. Opening a network subscription cannot: it connects to a system outside React and requires a lifecycle. This distinction tells you whether an Effect is appropriate. A purchase request caused by a specific click belongs to that event. A subscription that must exist while a component displays one account belongs to setup and cleanup tied to that account.
Write setup and cleanup as a pair. If setup attaches a listener, cleanup removes that same listener. If setup starts a timer or request, cleanup cancels or invalidates it. Cleanup runs before an Effect is replaced and when its component is removed. It should make an abandoned process unable to affect the current screen. A ref that merely prevents a second setup can hide a leak instead of repairing the lifecycle.
Completion order is not user-intent order
The user searches for re and immediately replaces it with react. Request A starts first, request B starts second, but B can finish first. If both completions unconditionally replace results, A eventually restores obsolete data. The network did nothing wrong: independent requests have no ordering promise. The component needs an acceptance rule that matches current user intent.
Associate each request with a generation or request ID. Only the active generation may publish success, failure or a loading-state change. A stale failure is as dangerous as a stale success because it can replace useful results with an unrelated error. In the kata, a start event changes the active ID; completions for other IDs have no effect. This captures the invariant without needing a real network or relying on arbitrary timeout durations.
Cancel work and reject obsolete results
AbortController can stop supported browser fetch work, saving resources and reducing unwanted completions. Still keep an acceptance guard: a request can complete just before cancellation, a later transformation can still be running, and not every library supports abort. The guard answers whether a result is relevant; cancellation answers whether work should continue. They are related controls with different guarantees.
An ignore flag local to an Effect is sufficient for many component-scoped requests. Cleanup flips the flag and aborts that request. A shared cache or concurrent requests for multiple resources need keys and a more explicit request model. Do not use one global latest-request counter for independent widgets unless the intended policy is that any new widget request cancels the others.
Client module
'use client';
import { useEffect, useState } from 'react';
export default function ClientResults({ query }: { query: string }) {
const [message, setMessage] = useState('Waiting');
useEffect(() => {
const controller = new AbortController();
let ignore = false;
setMessage('Loading');
async function load() {
try {
const response = await fetch(`/api/catalog?q=${encodeURIComponent(query)}`, {
signal: controller.signal
});
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
const body: unknown = await response.json();
if (!ignore) setMessage(JSON.stringify(body));
} catch (error) {
if (!ignore) setMessage(error instanceof Error ? error.message : 'Request failed');
}
}
void load();
return () => { ignore = true; controller.abort(); };
}, [query]);
return <p role="status">{message}</p>;
}Make dependencies and tests describe the process
An Effect captures values from a render. If it uses query, the process should be replaced when query changes. Removing query from dependencies does not optimize the process; it disconnects synchronization from the value it is supposed to track. Move unrelated objects or helper creation when necessary, rather than suppressing the dependency contract to stop reruns you have not explained.
Development Strict Mode deliberately exercises additional setup and cleanup behavior. Treat duplicate observations as a prompt to inspect lifecycle ownership before removing safeguards. A meaningful test controls completion order: start A, start B, finish B, then finish A and assert that B remains visible. Also test unmount and stale errors. These assertions check the user-facing guarantee, not an incidental count of Effect invocations.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEDebouncing is a complete solution to request races.
- A more accurate model
It reduces request frequency but does not impose completion order. Accept results by current request identity.
- How to check it
R05 explains cleanup and ignoring obsolete fetch results; the effects kata deliberately reverses completion order.
- CLAIM TO CHALLENGESuppressing the second development setup fixes an Effect leak.
- A more accurate model
A one-time flag can hide missing cleanup. Setup must have a corresponding cleanup for unmount and dependency changes.
- How to check it
R05 discusses development setup and cleanup checks and synchronization lifecycles.
Mistakes to catch in your own code
- Ignoring stale successes but accepting stale errors still breaks the screen.
- Debouncing reduces requests but does not guarantee response order.
- A development-only duplicate setup is not a reason to skip cleanup.
Write it by hand
JavaScript logic playground
Accept only the active request
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({events}). Event types are start with id, resolve with id and data, reject with id and error, and unmount. Request IDs are unique positive integers.
- Initial output is {status:"idle", data:null, error:null}. start clears data/error and sets loading. Only the active ID may resolve or reject. unmount freezes the state and ignores all later events.
- Return the final state. This synchronous event reducer checks an ordering policy; it does not run fetch or an Effect.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 5 test cases
- Old success cannot replace current result
Input
{ "events": [ { "type": "start", "id": 1 }, { "type": "start", "id": 2 }, { "type": "resolve", "id": 2, "data": [ "react" ] }, { "type": "resolve", "id": 1, "data": [ "re" ] } ] }Expected
{ "status": "success", "data": [ "react" ], "error": null } - Old error is ignored
Input
{ "events": [ { "type": "start", "id": 1 }, { "type": "start", "id": 2 }, { "type": "reject", "id": 1, "error": "timeout" } ] }Expected
{ "status": "loading", "data": null, "error": null } - Unmount freezes state
Input
{ "events": [ { "type": "start", "id": 1 }, { "type": "unmount" }, { "type": "resolve", "id": 1, "data": "late" } ] }Expected
{ "status": "loading", "data": null, "error": null } - Active error is visible
Input
{ "events": [ { "type": "start", "id": 3 }, { "type": "reject", "id": 3, "error": "unavailable" } ] }Expected
{ "status": "error", "data": null, "error": "unavailable" } - No active request
Input
{ "events": [ { "type": "resolve", "id": 9, "data": "unsolicited" } ] }Expected
{ "status": "idle", "data": null, "error": null }
Reveal the worked solution and reasoning
function solve(input) {
let active = null;
let mounted = true;
let state = { status: 'idle', data: null, error: null };
for (const event of input.events) {
if (!mounted) continue;
if (event.type === 'unmount') { mounted = false; continue; }
if (event.type === 'start') {
active = event.id;
state = { status: 'loading', data: null, error: null };
} else if (active !== null && event.id === active) {
if (event.type === 'resolve') state = { status: 'success', data: event.data, error: null };
if (event.type === 'reject') state = { status: 'error', data: null, error: event.error };
}
}
return state;
}Identity implements the acceptance rule independently of timing. The model guards errors as well as data.
Unmount is terminal in this trace. A new component instance would have a fresh trace and fresh initial state.
Verify it in a real Next.js application
Next.js application lab
Build and repair a browser search race
Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect the shipped /catalog page first: its form navigates with URL parameters and its reads happen on the server. Debounced browser fetching is an extension, not the behavior of that form.
- Build a separate small client search component against /api/catalog. Read its JSON products field, model loading/error/empty states, and add a request identity plus effect cleanup.
- Use controlled test interception or a local mock to delay the first query longer than the second. Repeat with an old failing request arriving after a newer successful request.
- Navigate away while a request is pending, then repeat with AbortController cleanup and the acceptance guard enabled. Keep this experiment distinct from the original server-rendered catalogue.
Check the behavior
- The latest query keeps its results after an earlier response finishes.
- An obsolete failure cannot replace the current success.
- A completion from an abandoned component does not publish a new view.
- The original URL-driven catalogue still works when the client search extension is removed.
Review the application reasoning
Use controlled response ordering rather than hoping network latency reproduces the race.
Cancellation saves resources where supported; request identity decides which completion may update the current view. The kata verifies that policy, while the extension verifies its lifecycle integration.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01Where should a save request run?
If saving is caused by a user pressing Save, it belongs to that event or a form action. If the product requires continuous synchronization, I would model that lifecycle explicitly with cleanup and debouncing. An Effect watching every field is not automatically equivalent to a deliberate save operation and can send unintended writes.
Follow-up questions
- How would autosave handle navigation?
- Which values are derived without an Effect?
- React: synchronizing with effectsOfficial documentation
- React: you might not need an effectOfficial documentation
02Why can a later search show an earlier result?
Request start order does not determine completion order. The UI accepted a response without checking whether its request still represents the active query. I would attach an identity to each request and accept both success and failure only for the current identity, while aborting obsolete work when supported.
Follow-up questions
- Why is debouncing insufficient?
- Can cancellation arrive too late?
- React: synchronizing with effectsOfficial documentation
03How do you respond to an Effect running twice in development?
I inspect whether setup has a matching cleanup and whether repeated setup leaves duplicate resources. Development checks help reveal missing lifecycle logic. I would not add a one-time flag merely to make the log quiet, because it may leave the real unmount or dependency-change case broken.
Follow-up questions
- What does cleanup need to undo?
- How do you test the production behavior separately?
- React: synchronizing with effectsOfficial documentation
04Should every Next.js page fetch inside useEffect?
No. Data required for the initial server-rendered screen can often be read in an async Server Component. Client fetching remains useful for interactive or live browser behavior. Choose the owner from the user experience and authorization boundary rather than moving all reads into Effects by habit.
Follow-up questions
- What happens to loading and SEO in a client-only fetch?
- When would a client query library help?
- Fetching dataOfficial documentation
- React: you might not need an effectOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- React: synchronizing with effectsOfficial documentation
- React: you might not need an effectOfficial documentation
- Fetching dataOfficial documentation
- CallMissed Next.js engineering assignmentEmployer assignment
- DejaBlue software interview exerciseEmployer assignment