Interested in our next book? Learn more about Building Large-scale JavaScript Web Apps with React

Rendering Pattern

React Server Components

The React team are working on zero-bundle-size React Server Components, which aim to enable modern UX with a server-driven mental model. This is quite different to Server-side Rendering (SSR) of components and could result in significantly smaller client-side JavaScript bundles.

The direction of this work is exciting, and while it isn’t yet production ready, is worth keeping on your radar. The following resources may be of interest:


Server-side rendering limitations

Today’s Server-side rendering of client-side JavaScript can be suboptimal. JavaScript for your components is rendered on the server into an HTML string. This HTML is delivered to the browser, which can appear to result in a fast First Contentful Paint or Largest Contentful Paint.

However, JavaScript still needs to be fetched for interactivity which is often achieved via a hydration step. Server-side rendering is generally used for the initial page load, so post-hydration you’re unlikely to see it used again.

With React Server Components, our components can be refetched regularly. An application with components which rerender when there is new data can be run on the server, limiting how much code needs to be sent to the client.

[RFC]: Developers constantly have to make choices about using third-party packages. Using a package to render some markdown or format a date is convenient for us as developers, but it increases code size and hurts performance for our users

NoteWithMarkdown.js
1// *Before* Server Components
2import marked from "marked"; // 35.9K (11.2K gzipped)
3import sanitizeHtml from "sanitize-html"; // 206K (63.3K gzipped)
4
5function NoteWithMarkdown({text}) {
6 const html = sanitizeHtml(marked(text));
7 return (/* render */);
8}

Server Components

React’s new Server Components compliment Server-side rendering, enabling rendering into an intermediate abstraction format without needing to add to the JavaScript bundle. This both allows merging the server-tree with the client-side tree without a loss of state and enables scaling up to more components.

Server Components are not a replacement for SSR. When paired together, they support quickly rendering in an intermediate format, then having Server-side rendering infrastructure rendering this into HTML enabling early paints to still be fast. We SSR the Client components which the Server components emit, similar to how SSR is used with other data-fetching mechanisms.

This time however, the JavaScript bundle will be significantly smaller. Early explorations have shown that bundle size wins could be significant (-18-29%), but the React team will have a clearer idea of wins in the wild once further infrastructure work is complete.

[RFC]: If we migrate the above example to a Server Component we can use the exact same code for our feature but avoid sending it to the client - a code savings of over 240K (uncompressed):

NoteWithMarkdown.server.js
1import marked from "marked"; // zero bundle size
2import sanitizeHtml from "sanitize-html"; // zero bundle size
3
4function NoteWithMarkdown({text}) {
5 // same as before
6}

Automatic Code-Splitting

It’s been considered a best-practice to only serve code users need as they need it by using code-splitting. This allows you to break your app down into smaller bundles requiring less code to be sent to the client. Prior to Server Components, one would manually use React.lazy() to define “split-points” or rely on a heuristic set by a meta-framework, such as routes/pages to create new chunks.

PhotoRenderer.js
1// *Before* Server Components
2import React from "react";
3
4// one of these will start loading *when rendered on the client*:
5const OldPhotoRenderer = React.lazy(() => import("./OldPhotoRenderer.js"));
6const NewPhotoRenderer = React.lazy(() => import("./NewPhotoRenderer.js"));
7
8function Photo(props) {
9 // Switch on feature flags, logged in/out, type of content, etc:
10 if (FeatureFlags.useNewPhotoRenderer) {
11 return <NewPhotoRenderer {...props} />;
12 } else {
13 return <PhotoRenderer {...props} />;
14 }
15}

Some of the challenges with code-splitting are:

  • Outside of a meta-framework (like Next.js), you often have to tackle this optimization manually, replacing import statements with dynamic imports.
  • It might delay when the application begins loading the component impacting the user-experience.

Server Components introduce automatic code-splitting treating all normal imports in Client components as possible code-split points. They also allow developers to select which component to use much earlier (on the server), allowing the client to fetch it earlier in the rendering process.

PhotoRenderer.server.js
1import React from "react";
2
3// one of these will start loading *once rendered and streamed to the client*:
4import OldPhotoRenderer from "./OldPhotoRenderer.client.js";
5import NewPhotoRenderer from "./NewPhotoRenderer.client.js";
6
7function Photo(props) {
8 // Switch on feature flags, logged in/out, type of content, etc:
9 if (FeatureFlags.useNewPhotoRenderer) {
10 return <NewPhotoRenderer {...props} />;
11 } else {
12 return <PhotoRenderer {...props} />;
13 }
14}

Will Server Components replace Next.js SSR?

No. They are quite different. Initial adoption of Server Components will actually be experimented with via meta-frameworks such as Next.js as research and experimentation continue.

To summarize a good explanation of the differences between Next.js SSR and Server Components from Dan Abramov:

  • Code for Server Components is never delivered to the client. In many implementations of SSR using React, component code gets sent to the client via JavaScript bundles anyway. This can delay interactivity.
  • Server components enable access to the back-end from anywhere in the tree. When using Next.js, you’re used to accessing the back-end via getServerProps() which has the limitation of only working at the top-level page. Random npm components are unable to do this.
  • Server Components may be refetched while maintaining Client-side state inside of the tree. This is because the main transport mechanism is much richer than just HTML, allowing the refetching of a server-rendered part (e.g such as a search result list) without blowing away state inside (e.g search input text, focus, text selection)

Some of the early integration work for Server Components will be done via a webpack plugin which:

  • Locates all Client components
  • Creates a mapping between IDs => chunk URLs
  • A Node.js loader replaces imports to Client components with references to this map.
  • Some of this work will require deeper integrations (e.g with pieces such as Routing) which is why getting this to work with a framework like Next.js will be valuable.

As Dan notes, one of the goals of this work is to enable meta-frameworks to get much better.


Learn more and share feedback with the React team

To learn more about this work, watch the talk from Dan and Lauren, read the RFC and do check out the Server Components demo to play around with this work. With thanks to Sebastian Markbåge, Lauren Tan, Joseph Savona and Dan Abramov for their work on Server Components.

Interesting relevant threads: