How do you fetch data in React?
IntermediateReact interview questionBy UIRound, updated 17 November 2026
Short answer
The basic way to fetch data in React is to call fetch inside useEffect, store the result in state, and abort the request in the cleanup so a stale response cannot overwrite a newer one. Most production apps use a library such as TanStack Query for caching and deduplication. In frameworks like Next.js, Server Components fetch on the server with async/await, and use() with Suspense reads promises on the client.
Fetching in useEffect
An effect runs after render, which is the right moment to start a request that depends on props.
import { useEffect, useState } from "react";
function UserProfile({ userId }) {
const [result, setResult] = useState(null); // { userId, user } or { userId, error }
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((user) => setResult({ userId, user }))
.catch((error) => {
if (!controller.signal.aborted) setResult({ userId, error });
});
return () => controller.abort();
}, [userId]);
if (result?.userId !== userId) return <p>Loading…</p>;
if (result.error) return <p>Could not load this user.</p>;
return <h1>{result.user.name}</h1>;
}Three details make this correct, and interviewers look for each one.
userIdis in the dependency array, so a new id starts a new request. How does useEffect work? covers dependencies and cleanup.- The cleanup aborts the request. When
userIdchanges or the component unmounts, React runs the cleanup first. - The result records which id it belongs to. Loading is derived: if the stored result is for a different id, we are loading. The old user is never shown under the new id.
fetch only rejects on network failure, not on a 404 or 500, so check res.ok yourself.
The race condition
Without the abort, this happens: the user picks user 1, then quickly user 2. Request 2 returns first and shows user 2. Then request 1 returns and overwrites the screen with user 1, while the UI says user 2 is selected. Responses do not arrive in the order you sent them.
Aborting solves it, because the old request's promise rejects with an AbortError and its .then never calls setResult. If an API cannot be cancelled, use an ignore flag set in the cleanup and check it before setting state. The same cleanup also handles React's StrictMode, which mounts, unmounts and mounts again in development, so you see a cancelled request in the network tab. That is expected.
Why libraries help
The effect above handles one request for one component. Real apps need more:
| Need | Hand-written effect | TanStack Query or similar |
|---|---|---|
| Cache shared across components | You build it | Built in, keyed by queryKey |
| Two components asking for the same data | Two requests | One request, deduplicated |
| Refetch when the window regains focus or reconnects | You build it | Built in |
| Retries on failure | You build it | Built in, configurable |
| Stale-while-revalidate | You build it | staleTime controls it |
| Mutations and invalidation | You build it | useMutation and invalidateQueries |
The same component with TanStack Query is short, and it passes the abort signal for you:
import { useQuery } from "@tanstack/react-query";
function UserProfile({ userId }) {
const { data, isPending, error } = useQuery({
queryKey: ["user", userId],
queryFn: async ({ signal }) => {
const res = await fetch(`/api/users/${userId}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
});
if (isPending) return <p>Loading…</p>;
if (error) return <p>Could not load this user.</p>;
return <h1>{data.name}</h1>;
}Fetched data is a copy of what the server owns, which is why it is called server state and deserves its own tool. What is TanStack Query and why use it? goes into the details.
Suspense and use()
React 19's use(promise) reads the value of a promise during render. If the promise is still pending, the component suspends, and the nearest <Suspense> boundary shows its fallback. Loading states move out of the component and into the tree.
The catch is that the promise must be stable. A promise created during a Client Component's render is a new promise on every render, so the component would suspend forever. The promise must come from a cache, a Suspense-enabled library or, most often, a Server Component.
Fetching in Server Components with Next.js
In the Next.js App Router, components are Server Components by default and can be async. They fetch on the server, close to the data, and send only the rendered result to the browser.
// app/users/[id]/page.jsx (Server Component)
import { Suspense } from "react";
import Comments from "./comments";
export default async function UserPage({ params }) {
const { id } = await params;
const user = await getUser(id); // awaited: needed for the heading
const commentsPromise = getComments(id); // not awaited: streamed in later
return (
<>
<h1>{user.name}</h1>
<Suspense fallback={<p>Loading comments…</p>}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
</>
);
}// app/users/[id]/comments.jsx
"use client";
import { use } from "react";
export default function Comments({ commentsPromise }) {
const comments = use(commentsPromise);
return <ul>{comments.map((c) => <li key={c.id}>{c.text}</li>)}</ul>;
}There is no effect, no loading state and no waterfall on the client: the page streams the heading first and the comments when they are ready. Server Components vs Client Components explains the boundary, and the data fetching and caching guide covers invalidation and optimistic updates.
Practise it
Handle every data-fetching state and Load a list, then the selected item's details, without races train the effect version properly. Implement useFetch() with loading, error, and cancellation wraps it in a hook, and Stop use() from suspending forever covers the Suspense catch. Build a data browser over a remote API and Build a mini React Query show what a library does for you.
Common follow-up questions
Why not make the effect function async?
async?An effect must return nothing or a cleanup function. An async function returns a promise, which React cannot use as a cleanup. Define an async function inside the effect and call it.
What is a request waterfall?
When a child starts its fetch only after its parent's fetch finishes and it renders. Each level adds a round trip. Fix it by starting independent requests together, higher up, or on the server.
Should I fetch in an event handler or an effect?
If the request is caused by a user action, such as submitting a form, do it in the handler. Use an effect only for data the component needs because it is on screen.
Is axios better than fetch?
axios better than fetch?It adds interceptors and rejects on HTTP errors, but fetch is built in and supports AbortController. The React patterns are the same with either.
Mistakes to avoid
Forgetting the cleanup, so a slow old response overwrites a new one
Treating a 404 as success because
fetchdid not rejectShowing the previous item's data while the next one loads
Creating a promise during a Client Component's render and passing it to
use()Copying fetched data into a global store by hand instead of using a server-state cache
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Handle every data-fetching state: loading, error with retry, empty results, no stale data and abortMedium35 min
- Load a list, then the selected item's details, without races: abort, ignore stale responses and cache by idMedium40 min
- Implement
useFetch()with loading, error, and cancellationMedium35 min - Stop
use()from suspending forever: a promise cache withreadandrefreshHard45 min - Build a data browser over a remote API: a shared cache, deduplicated requests, prefetch and no stale dataMedium45 min
- Build a mini React Query:
QueryClient,useQuery, prefix invalidation and garbage collectionHard60 min