Preventing stale updates and leaks from out-of-order async results.
01
01
Understand the problem
reacteffectsasync
02
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Stuck? AI Nudge Available
Get a conceptual hint to guide your logic without spoiling the final implementation.
03
03
Study the solution
The solution is waiting
Give it an honest attempt first — then compare your thinking with the full walkthrough.
04
04
Explore the playground snippets
Ignore-flag prevents a stale response winning
Run Playgroundimport { useState, useEffect } from 'react';
// Shorter queries resolve SLOWER, to force an out-of-order race.
function searchApi(q) {
const delay = Math.max(200, 1200 - q.length * 150);
return new Promise((res) => setTimeout(() => res(q ? 'Results for: ' + q : '—'), delay));
}
export default function App() {
const [query, setQuery] = useState('');
const [result, setResult] = useState('');
useEffect(() => {
let active = true;
searchApi(query).then((r) => { if (active) setResult(r); }); // ignore if superseded
return () => { active = false; };
}, [query]);
return (
<div style={{ fontFamily: 'sans-serif', padding: 24 }}>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type quickly" />
<p>{result}</p>
<p style={{ color: '#666' }}>The cleanup flag stops a slow early request from overwriting newer results.</p>
</div>
);
}05
05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.