Sub topic 12
When you do need an Effect: fetching data safely
This chapter assumes you know function components, useState, props, and the basics of useEffect and its dependency array. Earlier chapters showed many cases where an Effect is unnecessary. This one covers a case where it is the right tool: fetching data because a component is displayed.
Why fetching is a real Effect use case
An Effect synchronizes a component with a system outside React. The network is such a system. When a SearchResults component appears on screen with a given query, it has to stay in sync with the server's answer for that query. No user event caused that fetch. The component being displayed caused it.
Compare this with a form submission. When the user clicks "Register", the click is the cause, so the post call belongs in the event handler. When the user types in a search box, you could fetch in the onChange handler, but then every place that can change the query (typing, back-button navigation, a link, a default value) would need its own fetch call. An Effect says "whenever this component shows results for query, load them", and it covers all of those paths.
The rule of thumb is to ask why the code runs:
- Because the user did something specific: use an event handler.
- Because the component is on screen with certain props and state: use an Effect.
The basic Effect
Here is the example from the plan, with the pieces labeled.
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => {
if (!ignore) {
setResults(json);
}
});
return () => {
ignore = true;
};
}, [query]);
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}Three parts matter here:
- The Effect runs after React has rendered and updated the screen. Rendering stays a pure calculation, and the network call happens afterward.
- The dependency array
[query]tells React to re-run the Effect only whenquerychanges. - The cleanup function runs before the next Effect run and when the component unmounts. It sets
ignore = truefor the run that is ending.
The race condition the cleanup prevents
Without the ignore flag, this code has a bug. Network responses do not always arrive in the order the requests were sent.
Suppose the user types "react" and then quickly changes it to "reactive". Two requests are in flight. If the response for "react" arrives after the response for "reactive", the code calls setResults with the older data last. The input shows "reactive", but the list shows results for "react". This is a race condition.
The cleanup fixes it. When query changes, React runs the cleanup of the previous Effect before running the new one. That cleanup sets the old run's ignore to true. Each run has its own ignore variable, because each run is a separate call of the Effect function with its own closure. When the stale response finally arrives, its .then callback sees ignore === true and skips setResults.
The sequence looks like this:
The ignore flag does not cancel the request. The browser still sends it and the server still answers. The flag only prevents the stale answer from reaching state.
Cancelling the request with AbortController
If you also want to stop the network work, use an AbortController. Aborting makes the pending fetch reject with an AbortError, so you must handle that rejection.
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setError(null);
fetch('/api/search?q=' + encodeURIComponent(query), {
signal: controller.signal,
})
.then(response => {
if (!response.ok) {
throw new Error('Request failed with status ' + response.status);
}
return response.json();
})
.then(json => setResults(json))
.catch(err => {
if (err.name !== 'AbortError') {
setError(err);
}
});
return () => controller.abort();
}, [query]);
if (error) {
return <p>Something went wrong: {error.message}</p>;
}
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}Both approaches are valid. The ignore flag works with any asynchronous source, such as a promise from a library that has no abort support. AbortController also saves bandwidth. Some code uses both.
Common errors
Forgetting the cleanup
An Effect with no cleanup works in simple tests and fails under fast input or slow networks. The failure is intermittent, which makes it hard to reproduce. Always ask what happens if the dependency changes while the request is still pending.
Fetching in an Effect and then chaining on the result
If the fetched data triggers state that triggers another Effect that triggers another fetch, you have the chain pattern from an earlier chapter. Where possible, compute the second request from values you already have, or do the follow-up work in one async function inside the same Effect.
Missing or wrong dependencies
Every reactive value the Effect reads must appear in the dependency array. If the Effect reads query and page but the array lists only [query], the Effect will not re-run when page changes, and the results go out of date. The React linter rule react-hooks/exhaustive-deps catches this. Fix the code, not the lint warning.
Using an `async` function as the Effect callback
This is wrong:
useEffect(async () => {
const response = await fetch('/api/data');
setData(await response.json());
}, []);An async function always returns a promise, but React expects the Effect to return either nothing or a cleanup function. Define an inner async function and call it, or use .then chains as in the examples above.
useEffect(() => {
let ignore = false;
async function load() {
const response = await fetch('/api/data');
const json = await response.json();
if (!ignore) {
setData(json);
}
}
load();
return () => {
ignore = true;
};
}, []);Being surprised by two requests in development
In development with Strict Mode, React runs every Effect twice on mount: setup, cleanup, setup again. This checks that your cleanup works. You will see two requests for the same URL. That is expected, and it does not happen in production. If the second request causes a visible bug, the cleanup is incomplete. Do not remove Strict Mode or add a "has run" ref to hide the symptom.
Loading state
The earlier examples show an empty list while the request is pending. Users cannot tell "loading" from "no results". You can track loading as part of the Effect, but keep in mind the earlier rule about derived state: do not store what you can calculate.
import { useState, useEffect } from 'react';
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const [loadedQuery, setLoadedQuery] = useState(null);
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => {
if (!ignore) {
setResults(json);
setLoadedQuery(query);
}
});
return () => {
ignore = true;
};
}, [query]);
const isLoading = loadedQuery !== query;
return (
<>
{isLoading && <p>Loading...</p>}
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</>
);
}isLoading is calculated during render by comparing the query that was loaded with the current query. There is no separate setIsLoading(true) call inside the Effect, so there is no state that can fall out of sync with the data.
Effects versus other options
Writing fetch Effects by hand in every component has limits. You must remember cleanup, error handling, and loading state each time. Fetched data is not cached, so navigating away and back fetches again. Effects do not run on the server, so server-rendered HTML contains no data. When a request in a child can only start after the parent has rendered and fetched, requests form a waterfall and pages load slowly.
| Approach | Good for | Cost |
|---|---|---|
| Effect with cleanup | Small apps, one-off requests, learning how it works | You write caching, deduplication, and error handling yourself |
| Data-fetching library (such as TanStack Query or SWR) | Apps with many requests that share data | An added dependency |
| Framework data loading (such as a router loader or server components) | Apps that render on the server or need early fetching | Tied to the framework |
| Custom hook wrapping an Effect | Sharing the fetch logic across components | You still maintain the logic in one place |
A common middle step is to extract your Effect into a custom hook so components stay short.
import { useState, useEffect } from 'react';
function useSearch(query) {
const [results, setResults] = useState([]);
useEffect(() => {
let ignore = false;
fetch('/api/search?q=' + encodeURIComponent(query))
.then(response => response.json())
.then(json => {
if (!ignore) {
setResults(json);
}
});
return () => {
ignore = true;
};
}, [query]);
return results;
}
function SearchResults({ query }) {
const results = useSearch(query);
return (
<ul>
{results.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}A checklist for fetch Effects
- Is the fetch caused by the component being displayed, not by a user action? If a user action caused it, use an event handler.
- Does the Effect return a cleanup function that ignores or aborts stale requests?
- Does the dependency array list every reactive value the Effect reads?
- Are errors handled, including non-2xx responses, which
fetchdoes not reject on its own? - Is the callback a regular function, with any
asynccode in an inner function? - Does the code behave correctly when Strict Mode runs it twice?
Exercise
A component fetches /api/user/ plus a userId prop inside an Effect with the dependency array [userId] and no cleanup. A user clicks quickly through profiles 1, 2, and 3. The page ends up showing the data for profile 2 even though the URL says profile 3. What caused this, and how do you fix it?
Show answer
The responses arrived out of order. The response for profile 2 came back after the response for profile 3 and overwrote it in state, a race condition. Fix it by returning a cleanup function that sets a per-run ignore flag to true and by calling setState only when ignore is false. Alternatively, create an AbortController, pass its signal to fetch, call controller.abort() in the cleanup, and ignore the resulting AbortError in the catch handler.
Exercise
You see two identical network requests on mount in development, but only one in production. Is this a bug, and what should you check?
Show answer
It is expected. Strict Mode runs the Effect setup, cleanup, and setup again in development to test your cleanup. Check that the cleanup correctly ignores or aborts the first request, so the second request's result is the one that ends up in state. Do not add a ref to block the second run.