Data fetching in effects
Fetching data inside useEffect with loading and error state, and the honest limits of the pattern before you reach for a data-fetching library.
useEffect and synchronizing with external systemsForms and controlled inputs
Data fetching in effects
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Fetching inside useEffect means calling fetch or a library like axios in the effect body, storing the result in state, and letting that state drive the render.
- A fetch has at least three states worth tracking — loading, error, and data — and a component that only tracks data will render stale or broken UI while a request is in flight or after it fails.
- The dependency array still governs re-fetching: if the effect reads a value like a search term or an id, that value belongs in the array so changing it triggers a new request.
- This pattern has no built-in caching, so navigating away and back re-fetches data you already had, and two components fetching the same resource both hit the network independently.
- It has no request deduplication, and it is vulnerable to race conditions where a slower, earlier request resolves after a faster, later one and overwrites the UI with stale data — the next lesson deals with this directly.
- These aren't reasons to avoid useEffect for fetching while you're learning it; they're the specific, well-known gaps that a dedicated data-fetching library closes later in this roadmap.
The minimum viable fetch
Here’s the smallest version of fetching data on mount:
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("/api/users")
.then((res) => res.json())
.then((data) => setUsers(data));
}, []);
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
This works, right up until the network is slow, or fails, or the user does something before the data arrives. It renders an empty list while loading — indistinguishable from “there genuinely are no users” — and if the fetch rejects, nothing catches it, and the component just silently never updates. Those two gaps are exactly what loading and error state exist to close.
Three states, not one
A fetch that can succeed, fail, or still be in progress needs three pieces of state, not one:
function UserList() {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
setError(null);
fetch("/api/users")
.then((res) => {
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
})
.then((data) => setUsers(data))
.catch((err) => setError(err.message))
.finally(() => setIsLoading(false));
}, []);
if (isLoading) return <p>Loading users…</p>;
if (error) return <p>Couldn't load users: {error}</p>;
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Now every state the request can be in has a corresponding UI state. This is the shape you’ll see in a huge amount of real React code, and it’s worth being fluent in it even though, as this lesson will get to, it’s not the end of the story.
The same thing with axios looks almost identical, just with a different call and a response shape that’s already parsed:
useEffect(() => {
setIsLoading(true);
axios
.get("/api/users")
.then((res) => setUsers(res.data))
.catch((err) => setError(err.message))
.finally(() => setIsLoading(false));
}, []);
axios throws on a non-2xx response automatically and parses JSON for you, which is why the manual res.ok check and res.json() call disappear — otherwise the logic is the same three-state pattern.
When the fetch depends on something
Fetching on mount with [] is the simple case. Fetching based on a prop or piece of state — a search term, a selected id, a page number — means that value has to be in the dependency array, exactly as covered in the previous lesson:
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then((data) => setResults(data));
}, [query]);
return <ResultsList items={results} />;
}
Every time query changes, the effect fires again and issues a new request. That’s correct behavior — but it’s also exactly where this pattern’s problems start to show up.
The honest limits of this pattern
This component-level useEffect fetch is a real, widely-used pattern, and it’s worth knowing cold — but it’s also a stepping stone, not a destination, and it’s worth being upfront about why:
- No caching. If
SearchResultsunmounts and remounts with the samequerya second later, it fetches again from scratch. There’s no shared store of “we already have this.” - No deduplication. If two components on the same page both fetch
/api/users, that’s two network requests for identical data, because neither effect knows about the other. - Race conditions. If the user types quickly into the search box above, each keystroke can fire its own request, and nothing here guarantees the responses come back in the order they were sent. A slow response to an earlier query can arrive after a fast response to a later one and overwrite the UI with stale results.
That last point — the stale-request race — is common enough and subtle enough that it gets its own lesson next, with a concrete fix. The caching and deduplication gaps don’t get solved by writing cleverer useEffect code; they’re the specific reason a dedicated data-fetching library exists, which a later lesson in this roadmap, the case for a data-fetching library, covers in depth. The point of this lesson is to see the problem clearly, not to solve it with a library yet.
What the video covers
Andrew’s video walks through fetching data with axios in a React component, which is the exact mechanical core of this lesson — the request, the response handling, wiring the result into state. It’s a short, focused clip and doesn’t cover the loading/error-state structuring or the caching/race-condition caveats above in depth, so those sections fill in the rest of what a production component actually needs.
Where this fits
The race condition mentioned above — a stale response overwriting a fresher one — is common enough to deserve its own treatment. The next lesson, cleanup and race conditions in effects, fixes it with cleanup functions and AbortController.
Check yourself
What are the three pieces of state a component typically needs to track a fetch?
The data itself once it arrives, a loading flag for while the request is in flight, and an error value for when the request fails — all three need to be reflected in the UI, not just the data.
Why does a search term used inside a fetch effect need to be in the dependency array?
Because the effect needs to re-run and issue a new request whenever the search term changes; leaving it out of the dependency array means the effect keeps fetching with whatever search term was current the first time it ran.
What does it mean that this pattern has 'no caching'?
It means every time the effect runs, including when a component remounts after the user navigates away and back, it issues a fresh network request for data it may have already fetched moments earlier, instead of reusing a stored result.
Is fetching in useEffect a pattern to avoid?
No, it's a reasonable way to learn how fetching, loading state, and error state fit into a component, and it's still common in real code; the point is to recognize its specific gaps — caching, deduplication, and race conditions — so you know why a data-fetching library exists once your app outgrows it.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.