This talk is about server functions, but for the first part, I'll spend some time discussing React Server Components, or RSC. React 19 introduces several new features, but one of the most significant is RSC.
RSC stands for React Server Components, but when we say RSC, it often refers to the entire capability of running React on a server. So, RSC includes server components, server functions, and maybe more. One tricky thing is that RSC doesn't always require a runtime server. It can render several components at build time and generate static sites. So, RSC can even help with single page applications.
Technically, RSC's core capability is serialization, and it's provided by a React library, but to consume it, you need a framework or at least a bundler. Now, let's explore how server components work. Before server components existed, the concept was simple, as you know. Everything ran on the client. By the way, one of the strengths of React, as I see, is this intermediary representation, sometimes called the virtual DOM. Thanks to this, we can render a component multiple times before committing or apply certain extensions. Server components can be considered as one of those extensions.
Now, with server components, we have two types of components. Both are rendered separately and merged into a single representation. JSX elements are serialized into a JSON-like format and sent to the client. It's hard to show in this diagram, but the two rendering processes don't actually happen simultaneously. Because server components point to the client components, the rendering actually happens on the server at first. Once the client receives the JSX elements from the server, it renders the client components and merges the two results. So far, so good?
Let's see how this is implemented. I would like to explain the idea with code. Here, two code scenes basically represent client code and server code. They are pseudocode, but they are pretty close to the actual implementation in my framework. Let's look at the client code. CreateRoot is a function that should be familiar to most React users. On the other hand, createFromFetch is a new function from the React library and is typically used by frameworks. Now, on the server side, when it receives a request, the server renders the app component and creates a stream. This stream is called the RST payload that the client receives and renders. The key function here is renderToReadableStream.
Comments