React Server Components

Learn via video courses
Topics Covered

Overview

It takes a lot of time to conduct research, design, develop, and test modern applications. Several methods may be used to create modern apps, each of which has advantages and disadvantages and is designed to address a particular problem. There is no magic formula for creating contemporary apps.

What are React Server Components?

The zero-bundle-size React Server Components being developed by the React team seeks to provide modern UX with a server-driven conceptual framework. The client-side JavaScript bundles could be substantially smaller as a result of this as opposed to the Server-side Rendering (SSR) of components.

To increase the performance of React apps, it is possible to create React components that are rendered on the server side.

The frequent high volume of network requests performed while users wait for the page or data that is requested by the user to become accessible is one of the issues when designing applications with React:

what-are-react-server-components

For instance, calling APIs with the useEffect hook is the standard practice today for data retrieval:

However, the above-mentioned method is not incorrect, and it will always take some time for the user to receive anything useful due to the data fetching approach.

what-are-react-server-components-2

Server-side rendering is complemented by React's new Server Components, which allow rendering into a middle abstraction format without having to add to the JavaScript bundle. This enables scaling up to more components as well as integrating the server tree with the client-side tree without losing the state.

what-are-react-server-components-3

SSR cannot be substituted with server components. Together, they enable speedy rendering in an intermediate format, which is later converted into HTML via server-side rendering infrastructure, keeping early paintings responsive. As with previous data-fetching techniques, we SSR the Client components that the Server components emit.

Types of React Server Components

There are three types of React Server Components:

Server

Server components are those components that retrieve data from the server and render content. The client bundle does not contain its dependencies. There is no client-side interaction in the server components. The server components end with the .server.jsx file extension.

Client

These are the components that are rendered on the client side, that is, on the browser. These components have the .client.jsx extension.

Server components cannot be imported by the client components because the server components cannot be rendered by the browser. So, the question arises of how we get the React tree containing both client and server components, as illustrated above in the article. The answer to this question is by making use of props. The server components are rendered by the server and passed on to the client components as props.

Shared

In addition to components that are exclusive to the server or the client, you can also design cross-platform components. As long as the components adhere to all constraints for both the server and client components, this permits functionality to be shared across environments.

If the components do not contain either the .server.jsx or .client.jsx that means they have shared components, and they can be used by both the client and server.

types-of-react-server-components

Using React Server Components

React Server Components are in the experimental phase as of now. The React team has provided a demo using the React Server Components.

In that demo, in the /src folder, you will find various files. The client components are distinguished by the .client.js extension, while the server components are recognized by the .server.js extension. Components having only .js extensions are the shared files that can be used on both the server as well as the browser.

In the package.json file, you would encounter various experimental dependencies. react-fetch, react-fs(fs stands for file system), and react-pg(pg stands for PostgreSQL) are some of the experimental dependencies, and these are called the React IO(input/ output) libraries.

The npm start command starts to run the node server, and the Webpack build for the client side simultaneously.

In the following code, it can be observed that in the server script, the app.server.js is imported.

Now let us take a look at the NoteList.server.js file.

NoteList.server.js:

The react-fetch is the fetch API that allows you to send or get data across networks.

Though it is inadvisable using import db you can directly access the database and save and call data from the database.

It can also be observed that the SidebarNote component is imported and used like any other component in React.

Constraints

The React Server component has the following constraints, which need to be followed by the different components(client and server components):

  • Client components can only import other client components and cannot access server-exclusive functionality like the database.
  • Client-only functionality, such as state, and browser-only APIs, cannot be accessed by server components.

How React Server Components Work?

Let us now understand what happens when the React Server Components are rendered.

Since the server components are rendered in the server, the whole process of rendering the application starts at the server. Regardless of whether it renders other client components or server components, this "root" component is always a server component. Initially, the server gets a request to render. Based on the data given in the request, the server decides which server component and what properties to utilize.

The next step consists of serializing the root component and transforming the starting root server component into a tree of placeholder client component placeholders and base html elements. The browser will then handle the process of deserializing the tree, replacing the placeholders for the client with the actual client components, and rendering the finished product. The tree can then be serialized and sent to the browser at this moment.

The important point to remember is that the props must be serializable, which means functions or event handlers can not be passed on as props from server components.

Finally, the server sends the output to the browser, and the browser reconstructs the React tree which is to be rendered.

The React Server components can make use of the Suspense component, which displays until its children are fully loaded.

Why Use React Server Components?

Before React Server Components, every React component was a "client" component, meaning that it ran entirely within the browser. When you visit a React page, your browser first builds the React element tree, and then all the required React components are downloaded, and then renders the page to the DOM (in case of Server Side rendering, hydrates the DOM). Since you can install event handlers, maintain state, alter your React tree in response to events, and efficiently refresh the DOM in the browser, it's a good place for interactive React applications.

The React team has quoted the following in their RFC for React Server Components:

SSR and Server Components are complementary. SSR is primarily a technique to quickly display a non-interactive version of client components. You still need to pay the cost of downloading, parsing, and executing those Client Components after the initial HTML is loaded.

React Server Components attempt to completely replace the client-side functionality by doing the rendering and importing bundles on the server only, whereas, in the case of SSR, the aim is to render out an initial form of a component that subsequently operates like a normal client-side component. And so, we have some benefits of using React Server Components over Server Side Rendering and client-side rendering:

  • Whether they be the file system or database in the server components, you have direct access to your sources of data. The server can directly acquire the data you require without having to bounce through a public API endpoint, and as the data sources are closer to the server than the browser, the browser can access those data sources faster than the browser.
  • JavaScript packages do not need to be sent over the network to the client. On the server, the JavaScript is imported, run, and the output is received.

React Server Components essentially allow the server and the browser to focus on their strengths. Client components can concentrate on stateful interactivity, while server components can concentrate on fetching data and generating information. As a result, pages load more quickly, javascript bundle sizes are less, and users have a better overall experience.

Benefits and Limitations of React Server Components

There are various benefits that the React Server Components provide over the traditional react components.

  • React Server components can utilize server-only data sources, such as file systems, databases, and internal services. In other words, the component has total access to the environment of the node in which it is located. And this data can then be sent to the client at the initial render, thus eliminating API calls and improving performance.
  • React Server components can use server hooks. Hooks can be used to access server-side resources like the file system and share functionality in a similar way to regular hooks.
  • These components render native elements (for example- div) and client-side as well as other server-side elements.
  • The dependencies present in the server components are not imported onto the client-side(browser). This improves the performance of the application.
  • Additionally, server components can read GraphQL queries.
  • All regular imports in Client components are treated as potential code-split places by Server Components' automatic code-splitting. As a result, the client can fetch the component considerably earlier in the rendering process. They also enable developers to choose which component to utilize much sooner (on the server).

There are several restrictions/limitations with React Server Components because of how they are executed in a server-side environment.

  • No use of state is allowed (useState() is not supported). The component is not executing on the client and preserving state because it is just run once, and the outputs are delivered to the client.
  • The useEffect() lifecycle event is absent. Once more, this is because the component is not operating in the browser, where it would benefit from events and side effects.
  • There are no utility methods or custom hooks that rely on browser-only APIs or state or consequences. These are merely the consequences of the previous limitations.
  • Browser-only APIs cannot be used.
  • The React Server Components Server Components boost the AJAX network transfers to decrease the size of the JS bundle. Additionally, the server will provide a substantial amount of modified markup even when a user action might only cause a minor data update. And to solve this issue, at present, the developer has to write code for caching, making it a complex implementation.

Difference between React Server Components and Server Side Rendering (RSC vs SSR)

Server Side RenderingReact Server Components
Server Side rendering is the method where instead of rendering the application on the browser, the application is rendered on the server itself, and a static HTML file is sent to the browser, where the DOM is then hydrated. Therefore this method greatly increases the SEO as well as overall performance.The components known as server components are also rendered on the server side, but the difference is that they are not in HTML format. A unique format is used to render server components before they are streamed into the client.
While Server Side Rendering apps can be rerendered, doing so will result in the creation of a brand-new HTML page and the loss of any app state that may have been there. Therefore, when we employ server-side rendering, we typically only use it only one time for initial rendering.React Server Components can be rerendered at any time. To render our data again, server components may need to be fetched more than once. Regular re-fetching of our server components would not cause any state information on our client components to be lost, and the server will feed changes down.
With Server Side Rendering apps, especially with Next.js, we must utilize getServerProps(), which only functions at the top level of our page.React Server Components, however, can access server data sources such as databases from anywhere in the tree.

Conclusion

In this article, we learned the following:

  • React Server Components are an experimental feature aiming to have zero bundle size and create a faster application.
  • There are three types of components in React Server components:
    • Client components
    • Server components
    • Shared components
  • The client components are the traditional React components. They have a .client.js extension.
  • Server components are those components that are rendered on the server only and send the data in a particular format that is similar to that of JSON. They have a .server.js extension.
  • Shared components are those components that can be utilized both as server and client components. They have only .js as an extension.
  • The React Server Components provide a lot of benefits, such as directly accessing the server, sending pre-rendered components to the client, thus increasing the performance of the application, reducing bundle size to be imported by the browser, and automatic code splitting, among others.
  • There are some constraints to the React Server Components:
    • Client components can only import other client components and cannot access server-exclusive functionality like the database.
    • Client-only functionality, such as state, and browser-only APIs, cannot be accessed by server components.
  • Since the Server components are rendered on the server they have some restrictions like they cannot access the state(can not use useState), they cannot be interactive that is they do not support event handling, they cannot use browser-only APIs, etc.
  • Though Server components seem similar to Server Side Rendering both of these are different.
  • Server Side Rendering sends the static HTML file to the browser loaded with content, and then the browser hydrates the components, so the performance is increased.
  • Server Side Rendering apps lose state in case of rerendering, but that is not the case with the server components. The server components preserve the state of the application.