Sub topic 15
Fetching in Server Components
This chapter assumes you know async/await, React components and JSX, and basic HTTP status codes. You should also have seen the earlier chapters on useEffect fetching, request states, and TanStack Query. Here you will see how React Server Components (RSC) move fetching out of the browser and what that changes about the code you write.
What a Server Component is
A Server Component is a React component that renders only on the server. Its code never ships to the browser. The browser receives the rendered output, not the component function.
This has one direct consequence for fetching. A Server Component can be an async function, so it can await data in its body. There is no useEffect, no useState for loading and error flags, and no cleanup function.
Server Components need a framework or bundler that supports them. Next.js App Router is the most common example. A plain Vite project with create-react-app-style setup does not run them. Details such as default caching vary by framework and version, so check your framework's documentation.
The basic pattern
This is the example from the plan. The component awaits fetch, checks the status, and renders the list.
export default async function UserList() {
const response = await fetch('https://example.com/api/users');
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const users = await response.json();
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Compare it with the effect-based UserProfile from earlier chapters:
| Concern | Effect in a Client Component | Async Server Component |
|---|---|---|
| Where the request runs | Browser, after first render | Server, during render |
| Loading state | `useState` flag you manage | Suspense boundary (see below) |
| Error state | `useState` you manage | Error boundary |
| Cancellation | `AbortController` in cleanup | Not needed in your code |
| Stale responses | Possible without cleanup | Not possible, because no state is updated afterward |
| Code sent to browser | Component and fetch logic | Only the rendered result |
The response.ok check is still required. As in the first chapter, fetch resolves on a 404 or 500, so you must turn those into errors yourself.
Why the race condition goes away
Earlier you used cleanup to stop an old response from overwriting a newer one. That problem exists because a client component keeps state across renders, and a slow response can arrive after the inputs have changed.
A Server Component has no state and no effects. Each render is a fresh run: it receives its props, awaits its data, and produces output. When the user navigates, the framework requests a new render from the server. Nothing in your component is left waiting to call a setter.
Loading and errors move to boundaries
Without isLoading and error variables, the component still needs to show something while it waits, and something when the request fails. React handles both with boundaries placed above the component.
- A
<Suspense>boundary shows a fallback while the async component is not ready. - An error boundary shows a fallback when the component throws. This is why the example throws on a bad status instead of returning an error element.
In Next.js App Router, the loading.js and error.js files create these boundaries for a route segment. In other frameworks you can wrap the component yourself:
import { Suspense } from 'react';
import UserList from './UserList';
export default function UsersPage() {
return (
<main>
<h1>Users</h1>
<Suspense fallback={<p>Loading users...</p>}>
<UserList />
</Suspense>
</main>
);
}The heading renders immediately. The list streams in when its data is ready. This is the same Suspense idea from the previous chapter, but the thing that suspends is a server-side await instead of a client-side use call.
Avoiding waterfalls on the server
The waterfall problem from earlier still applies. If a parent awaits data and then renders a child that awaits its own data, the second request cannot start until the first finishes. Server-side waterfalls are usually cheaper than browser ones, because the server is often closer to the API, but they still add latency.
You have two main fixes. The first is to start independent requests together:
async function getUser(id) {
const response = await fetch(`https://example.com/api/users/${id}`);
if (!response.ok) {
throw new Error(`User request failed with status ${response.status}`);
}
return response.json();
}
async function getPosts(id) {
const response = await fetch(`https://example.com/api/users/${id}/posts`);
if (!response.ok) {
throw new Error(`Posts request failed with status ${response.status}`);
}
return response.json();
}
export default async function Dashboard({ userId }) {
const [user, posts] = await Promise.all([getUser(userId), getPosts(userId)]);
return (
<section>
<h1>{user.name}</h1>
<p>{posts.length} posts</p>
</section>
);
}Promise.all rejects as soon as one request fails. If one failure should not block the other, use Promise.allSettled and handle each result.
The second fix is to split the page into separate async components, each inside its own Suspense boundary. The server starts rendering them independently, and each part streams in when ready.
What Server Components cannot do
A Server Component runs once per render on the server. It cannot use:
useState,useReducer, oruseEffect- Event handlers such as
onClick - Browser APIs such as
windoworlocalStorage
If a part of the UI needs these, make it a Client Component. In Next.js and similar frameworks you do this with a 'use client' directive at the top of the file. A common design is a Server Component that fetches data and passes it as props to a Client Component that handles interaction.
// UserPage.jsx (Server Component)
import RenameButton from './RenameButton';
export default async function UserPage({ userId }) {
const response = await fetch(`https://example.com/api/users/${userId}`);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const user = await response.json();
return (
<div>
<h1>{user.name}</h1>
<RenameButton userId={userId} />
</div>
);
}Props passed from a Server Component to a Client Component must be serializable. Plain objects, arrays, strings, numbers, and similar values work. Functions and class instances generally do not.
Caching and freshness
Server fetching does not remove the caching question. It moves it. In the browser you used TanStack Query's query keys and stale times. On the server, caching is controlled by the framework, and defaults differ between frameworks and versions. Some frameworks cache fetch results, some cache whole rendered routes, and some offer options to revalidate after a time or after a mutation.
Read your framework's caching documentation before you rely on data being fresh or cached. A page that looks correct in development can serve stale data in production if you assume the wrong default.
Mutations also work differently. Instead of useMutation and invalidateQueries, frameworks typically offer server-side functions (such as Server Actions in Next.js) plus a way to revalidate the affected route or data. The goal is the same: change the data, then make sure the display reflects it.
Security notes
Server Components can read secrets such as API keys and database credentials, because their code never reaches the browser. Two cautions apply.
- Do not pass secrets or whole database records as props to a Client Component. Props are serialized and sent to the browser, so anything you pass is visible there.
- Keep server-only modules out of client files. Many frameworks offer a
server-onlypackage that causes a build error if a client file imports the module by mistake.
Common errors
- Adding
useEffectto a Server Component. The build fails or the hook throws. Move that logic to a Client Component. - Forgetting the
response.okcheck. A 500 response with an HTML body fails later atresponse.json()with a confusing parse error. - Sequential awaits for independent data. Each
awaitpauses the component. UsePromise.allwhen requests do not depend on each other. - Using a relative URL. Server-side
fetchhas no browser origin, so/api/usersmay fail. Use an absolute URL, or call the data source directly. - Assuming fresh data. Check how your framework caches.
Summary
Server Components let you fetch with a plain await inside the component. Loading and error states move to Suspense and error boundaries, and the race conditions that needed AbortController do not arise. You still check response.ok, avoid waterfalls, and think about caching. Interactive parts remain Client Components. The final chapter compares all the approaches directly.
Exercise
A Server Component fetches a user and then, in a child Server Component, fetches that user's posts. The page feels slow. The two requests do not depend on each other's data, only on the user ID. Name two ways to speed it up.
Show answer
First, fetch both in the parent with Promise.all([getUser(id), getPosts(id)]) so the requests start together, then pass the results down. Second, give each async component its own Suspense boundary so the server renders them independently and streams each when ready. Either removes the wait caused by one request starting only after the other finishes.
Exercise
Why does a Server Component not need an AbortController to prevent stale responses, and where do its loading and error states live instead?
Show answer
A Server Component has no state or effects, so no old response can call a setter after the inputs change. Each navigation triggers a fresh render. Loading is handled by a Suspense boundary above the component, and errors are handled by an error boundary that catches the error thrown when response.ok is false.