React Server Components
async function Component() {
const db = new Postgres({ password: '..', host: '..', port: '..' });
const movies = await db.select().from('movies');
return (
<div>
{movies.map(movie => {
return <div key={movie.id}>{movie.name}</div>;
})}
</div>
);
}
This is a React Server Component.
Notice how the component above reads information directly from a database. If we wanted to render this component in your browser, we could - when you request the web page we'd just need to send the database credentials down too. You'd connect to the db, render this component, await the query, and show the returned UI.
Now, we don't do this in practice because I would've just sent you my database password. So clearly, rendering this component in your browser doesn't make sense.
What can we do then? Browsers have been rendering React components since the dawn of time, surely we're not going to stop doing that are we?
Yes we are. For this component at least.
We're going to render this component on my database server. That's where my credentials are, that's where my database is, and that's where it would be convenient and fast to render it.
But then, how would I send you the UI that was returned from rendering? Components have never crossed boundaries like this before, especially not a big wide network boundary.
To solve this, the React team built a serialisation protocol - a fancy term that describes how the computed output of a component can be transformed into a specific format that can be sent across network boundaries.
Now when you visit my webpage, instead of sending the database credentials and the component to render, we simply send the computed output UI. Your browser receives it, deserialises it from its fancy format, and shows it on the page - movie results and all.
In my opinion, this is RSC: a new technology that allows a React component to be rendered in an environment different to the one it will ultimately be shown in.
The "server” in React Server Component really just describes a component that probably wasn't rendered in your browser. It could be in theory - but for one reason or another it made more sense to render that component on another computer.
It might be freshly rendered by that computer on each HTTP request, it might have been rendered 6 months earlier and then cached, it might have been rendered on a Cloudflare Worker in Melbourne or on a server in Seattle but it probably wasn't rendered in your browser. Your browser only received the output and showed it on your screen.