CHAPTER 4Server Components
React started in the browser (the client), and there it helped generate the DOM efficiently. But NextJS was the first framework to be able to properly use Server Components, which use the same code to generate HTML instead, just as if we wrote it on a buffer.
If you are learning React today, the best way to proceed is to just use Server Components as the first components you define and use, since they are a natural way of working (much like PHP or generating HTML directly).
If you first learned React for the client and got used to it, you might get confused by Server Components since your mental model might be tied to the client.
Server Components
In NextJS, by default, all components defined in a new file are Server Components, which allow the server to decide what type of rendering is necessary:
- Static: at compile time and saved to an HTML file.
- Dynamic: computed at runtime at each request.
- Streaming: sent asynchronously while the response is being assembled.
The details about how to select each mode depend on the data you render and the type of page.
Even if it is not necessary, to mark a server component as such, you can write this line at the beginning of the file:
"use server";
Fetching data
A typical web app will fetch some data from some API and embed it into the UI. This is straightforward with server components, you create an async
function which returns JSX by filling in the details of the objects you are showing:
// file: RandomUserList.tsx
const BASE_URL = `https://randomuser.me/api`;
const fetchRandomUsers = async (howMany: number) => {
const response = await fetch(`${BASE_URL}/?results=${howMany}`);
const { results: users } = await response.json();
return users;
};
export const RandomUserList = async ({ numUsers }: { numUsers: number }) => {
const users = await fetchRandomUsers(numUsers);
return (
<ul>
{users.map(({ name }) => (
<li>
{name.first} {name.last}
</li>
))}
</ul>
);
};
Data change frequency
By default, NextJS will render everything as a static page, but here it is important to understand when to render data.
Change Frequency | Type of Components | Render Time |
---|---|---|
Days | Server Components | Static (at build time) |
Hours, Minutes | Server Components | Dynamic (at request time) |
Seconds | Client Components | Client (DOM replacement) |
Rendering strategies
-
Static: compile pages in HTML files at build time, and distribute them to the edge servers.
-
Dynamic: generate HTML on the server, using data fetched at the time. There are many caching strategies, so that the server does the minimum amount of work.
-
Dynamic with Streaming: generate HTML on the server, and if parts of the page are slower, start sending the static parts first, and then send the rest as it comes.
-
Client: render pages on the client (using
fetch
on the client) and replace the DOM.