Course contentsShow
← React
Lesson 580 of 2,39616. useEffect for Data FetchingFree lesson

Why useEffect Doesn't Cancel Previous Fetches

Learning that React cleans up effects but doesn't automatically abort in-flight network requests from old renders.

Why useEffect Doesn't Cancel Previous Fetches

You'll learn why React's cleanup mechanism alone doesn't stop old network requests that are already in flight.

When you click a new search term before the previous request finishes, both network requests keep running in the background. React will run your cleanup function before the next effect runs, but cleanup only executes your code—it doesn't magically know about or cancel your fetch request.

React Cleans Up Effects, Not Network Requests

When useEffect re-runs because a dependency changed, React calls your cleanup function first. This gives you a chance to tidy up—remove event listeners, clear timers, etc. But if you've started a fetch() call, that HTTP request continues traveling to the server and back, completely independent of React's lifecycle.

Think of it like sending letters through the mail. If you send a letter, then immediately decide "wait, I want to send a different one instead," you can't reach into the postal system and pull the first letter back. Both letters arrive. React's cleanup is like you getting a reminder to do something—but the original letter is already gone.

The Core Problem

useEffect(() => {
  fetch(`/api/search?q=${searchTerm}`)
    .then(res => res.json())
    .then(data => setResults(data));
}, [searchTerm]);

This code has no cleanup function at all. Even if you add an empty cleanup, it won't affect the fetch—the request keeps going, the .then() callbacks will still fire, and setResults will still be called, potentially with stale data.

Key Takeaway: React's effect cleanup runs your cleanup code, but it's your responsibility to actually cancel or ignore ongoing async operations—React doesn't do it automatically.