Sub topic 15
Fetching in Server Components
This chapter assumes you know how useEffect fetching works, how loading and error states are modeled, and what a data library such as TanStack Query adds. It also assumes you have read the previous chapter on Suspense and the use hook.
Where the fetch runs
Every approach so far fetches in the browser. The component renders, the browser sends a request, and state updates when the response arrives. The user sees a loading state first.
A React Server Component (RSC) runs only on the server, in a framework that supports it, such as Next.js with the App Router. The server renders the component, and the output is sent to the browser. The component's code and its data never need to ship to the client as a bundle.
Because a Server Component can be an async function, it can await data directly while rendering.
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>
);
}This component has no useState, no useEffect, and no loading flag. The await pauses rendering on the server until the data is ready.
What changes
Several problems from earlier chapters shrink or disappear.
- Race conditions and cleanup. There is no effect and no state, so there is nothing to abort or ignore.
- Waterfalls. The server is usually closer to your API or database, so sequential requests cost less. Independent requests should still be started together, for example with
Promise.all. - Secrets. Server code can read private environment variables or query a database. That code never reaches the browser.
- Errors. A thrown error is handled by the framework's error boundary, not by an
errorstate you write. - Loading. You wrap a slow component in
Suspense. The framework can send the rest of the page first and stream the slow part when it is ready.
What does not change
Server Components cannot use state, effects, or event handlers. Anything interactive must live in a Client Component, which you mark with the 'use client' directive. A common pattern is to fetch in a Server Component and pass the result to a Client Component as props.
Server Components also render once per request. They do not update on their own when server data changes. For live data, or for data that changes as the user interacts, you still need a Client Component with a library such as TanStack Query.
Caching behavior is set by the framework, not by React. A fetch call may be cached, deduplicated, or run fresh depending on your framework and its version, so check its documentation.
Summary
Use Server Components for data that is needed to render the initial page, especially data that needs private credentials. Keep effect or query-library fetching for interactive and frequently changing data.
Exercise
A component needs the current user's list of orders on first page load, using a database password. A second component shows a search box that refetches results on every keystroke. Which kind of component fits each?
Show answer
The orders list fits a Server Component, because it needs data at first render and the password must stay on the server. The search box fits a Client Component using an effect or TanStack Query, because it responds to user input and refetches repeatedly.