More React answers

by Danny
Published 3 min read

Fetching in useEffect still works, but it brings waterfalls, race conditions and no caching. Learn when to use framework loaders, Server Components, TanStack Query or use() instead.

The short answer

#

For most apps, no. If you use a framework, load data on the server with Server Components or route loaders. In a client-only app, use a data library such as TanStack Query. A hand-written useEffect fetch is still fine for small, one-off cases, as long as you handle cancellation.


_11
// Client-side, with TanStack Query
_11
function Profile({ id }: { id: string }) {
_11
const { data, isPending, error } = useQuery({
_11
queryKey: ['user', id],
_11
queryFn: ({ signal }) => fetch(`/api/users/${id}`, { signal }).then((r) => r.json()),
_11
});
_11
_11
if (isPending) return <Spinner />;
_11
if (error) return <ErrorMessage error={error} />;
_11
return <h1>{data.name}</h1>;
_11
}

Why it happens

#

useEffect runs after the component has rendered and the browser has painted. Fetching there means the user first sees an empty or loading screen, then the request starts. That ordering causes several problems that every team ends up solving by hand:

  • Waterfalls. A parent fetches, renders a child, and only then does the child start its own fetch. Each level adds a full round trip.
  • Race conditions. If the id changes quickly, an older response can arrive after a newer one and overwrite it.
  • No caching or sharing. Two components that need the same data each fetch it, and navigating back refetches everything.
  • No server rendering. Effects do not run on the server, so the HTML arrives without the data.
  • Double requests in development. Strict Mode mounts components twice to surface missing cleanup, so an effect without an abort fires two requests.

The React docs themselves recommend a framework's data fetching or a client-side cache over raw effects for these reasons.

How to fix it

#

Fetch on the server with Server Components

In a framework that supports React Server Components, such as the Next.js App Router, a server component can be async and await its data directly. The data is ready before any HTML is sent, and nothing extra ships to the browser.


_10
// app/users/[id]/page.tsx
_10
export default async function UserPage({ params }: { params: Promise<{ id: string }> }) {
_10
const { id } = await params;
_10
const user = await getUser(id);
_10
return <h1>{user.name}</h1>;
_10
}

Wrap slower parts in Suspense so the rest of the page can stream in first.

Use your router's loaders

Routers such as React Router (in framework mode) and TanStack Router let each route declare a loader. The router starts every loader for a navigation in parallel, before rendering, which removes waterfalls.


_10
// React Router route module
_10
export async function loader({ params }: Route.LoaderArgs) {
_10
return getUser(params.id);
_10
}
_10
_10
export default function User({ loaderData }: Route.ComponentProps) {
_10
return <h1>{loaderData.name}</h1>;
_10
}

Use a data library on the client

For client-heavy apps, TanStack Query (or SWR) gives you caching, deduplication, retries, background refresh and request cancellation. Data that changes because of user input, such as search results or infinite lists, fits this well. useSuspenseQuery lets you use Suspense boundaries for the loading state instead of isPending checks.

Read a promise with use()

React 19's use API reads a promise and suspends until it resolves. The key rule is that the promise must be created outside the component's render, for example in a Server Component that passes it down, or in a cache, otherwise a new promise is made on every render.


_16
// Server Component starts the request, does not await it
_16
export default function Page() {
_16
const commentsPromise = getComments();
_16
return (
_16
<Suspense fallback={<Spinner />}>
_16
<Comments commentsPromise={commentsPromise} />
_16
</Suspense>
_16
);
_16
}
_16
_16
// Client Component
_16
'use client';
_16
function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
_16
const comments = use(commentsPromise);
_16
return comments.map((c) => <p key={c.id}>{c.text}</p>);
_16
}

In a real project the 'use client' directive goes at the top of the client component's own file.

If you do use useEffect, clean up

For a small widget or prototype, an effect is acceptable. Abort the request in the cleanup so stale responses are ignored and Strict Mode does not leave a second request running.


_12
useEffect(() => {
_12
const controller = new AbortController();
_12
_12
fetch(`/api/users/${id}`, { signal: controller.signal })
_12
.then((r) => r.json())
_12
.then(setUser)
_12
.catch((err) => {
_12
if (err.name !== 'AbortError') setError(err);
_12
});
_12
_12
return () => controller.abort();
_12
}, [id]);

Common pitfalls

#
  • Turning off Strict Mode to stop double fetches. That hides the missing cleanup instead of fixing it.
  • Making the effect callback async****. An effect must return nothing or a cleanup function, not a promise. Define an async function inside the effect and call it.
  • Creating the promise for use during render. use(fetch(url)) inside a client component refetches on every render and can loop. Create it once, outside render.
  • Fetching in effects to sync props into state. If you can compute a value from props, do it during render instead.
  • Using effects for mutations. Send form submissions and button actions from the event handler or a form action, not from an effect watching state.
#

Was this resource helpful?