React·Advanced·Coding·1 min read
How do you prevent stale network responses from winning?
Short interview answer
Abort the obsolete request when possible and guard state commits with request identity or an ignore flag scoped to the effect. Cleanup marks the old synchronization as obsolete. Debouncing alone does not solve response races.
Example
useEffect(() => { let ignore = false; fetch(`/api/users/${userId}`) .then((r) => r.json()) .then((data) => { if (!ignore) setUser(data); }); return () => { ignore = true; }; // last effect to run wins}, [userId]);Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.