Production engineering workshop · 45 MIN
React · Prevent stale requests from replacing current state
An effect owns the lifetime of the asynchronous work it starts.
Changing a resource ID starts a new effect. Cleanup cancels the old request and prevents the old handler from committing results. A discriminated state makes loading and errors explicit. AbortController cancels fetch, while the active guard protects the commit point even when a transport does not cooperate. React development Strict Mode probes setup and cleanup, so the effect must tolerate being started and stopped.
First reproduce the normal path. Then force a failure at each boundary and inspect what remains true.
Read the example
import {useEffect,useState} from "react";
type State = {status:"loading"} | {status:"error";message:string} | {status:"success";name:string};
export function useLearner(id:string, retry=0): State {
const [state,setState] = useState<State>({status:"loading"});
useEffect(() => {
const controller = new AbortController();
let active = true;
setState({status:"loading"});
async function load() {
try {
const response = await fetch(`/api/learners/${encodeURIComponent(id)}`, {signal:controller.signal});
if (!response.ok) throw new Error("Could not load learner");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("name" in data) || typeof data.name !== "string")
throw new Error("Invalid learner response");
if (active) setState({status:"success",name:data.name});
} catch (error) {
if (active) setState({status:"error",message:error instanceof Error ? error.message : "Request failed"});
}
}
void load();
return () => { active=false; controller.abort(); };
},[id,retry]);
return state;
}Check the expected output
Review the behavior in the stated project environment.
Your challenge
Create a React TypeScript component using this hook. Provide a same-origin JSON endpoint returning {name:string}. Test fast navigation A → B while A finishes last, unmount during a request, invalid JSON and a 500 response. Render each state and a retry button using a retry counter dependency.
Solution cost: O(1) state transitions plus response parsing. time · One response and controller per mounted hook. space
Common trap
Suppressing the dependency linter can retain a stale ID. This hook is illustrative; a framework data layer can also handle caching and deduplication.
Study the project implementation
import {useEffect,useState} from "react";
type State = {status:"loading"} | {status:"error";message:string} | {status:"success";name:string};
export function useLearner(id:string, retry=0): State {
const [state,setState] = useState<State>({status:"loading"});
useEffect(() => {
const controller = new AbortController();
let active = true;
setState({status:"loading"});
async function load() {
try {
const response = await fetch(`/api/learners/${encodeURIComponent(id)}`, {signal:controller.signal});
if (!response.ok) throw new Error("Could not load learner");
const data: unknown = await response.json();
if (!data || typeof data !== "object" || !("name" in data) || typeof data.name !== "string")
throw new Error("Invalid learner response");
if (active) setState({status:"success",name:data.name});
} catch (error) {
if (active) setState({status:"error",message:error instanceof Error ? error.message : "Request failed"});
}
}
void load();
return () => { active=false; controller.abort(); };
},[id,retry]);
return state;
}Further reading: Official documentation