Introduction to React Server Components!
Tags: react, nextjs, webdev
Published: 2023-07-29 15:43:54

For a React developer, there are various ways to decide how we want to render a component. We could use the default client-side rendering (CSR) or choose between static site generation (SSG) and server-side rendering (SSR) based on the app requirements and interactivity. Now, we have got yet another way to work with React!

React Server Components is a new feature in React that allows developers to build more performant and flexible apps by blending server-side rendering with the interactivity of client-side JavaScript. In this beginner-friendly introduction blog, we will cover the basics of React Server Components and why they are useful.

This topic was recently introduced to me by the keynote speaker [Tejas Kumar](https://twitter.com/TejasKumar_) at the React Nexus 2023 Conference and by [Tapas Adhikary](https://twitter.com/tapasadhikary) at the JSLovers meet-up. Hence, I am here to share my understanding through this article!

## What are React Server Components (RCS)?

React Server Components are a new feature in React that allows developers to write components that can be rendered on both the server and the client. This means that the initial render of the component would happen on the server, which can improve performance and reduce the time it takes for a user to see the content. After the initial render, the component can be hydrated on the client, which allows for interactivity and dynamic updates.

## Why use React Server Components?

React Server Components allow you to render your React components on the server instead of the client. This has several benefits:

- **Zero Bundle Size**: Server components don't bundle any code to the client. So if you use any third-party libraries inside a server component, it won't affect your client bundle size. This can significantly reduce your bundle size.
- **Faster Performance**: Data fetching is faster since it happens on the server instead of the client. Server components have direct access to server data sources like databases and file systems.
- **Better SEO**: Since the initial render of the component happens on the server, search engines can index the content more easily.
- **More flexible architecture**: React Server Components allow developers to write components that can be rendered on both the server and the client, which can make it easier to build complex applications.
- **Code Splitting**: Importing client components from server components act as a code-splitting. Only the client components needed for the initial render will be bundled, others will be loaded lazily.

So in summary, server components allow you to colocate your data-fetching logic with your UI components. This improves performance and bundle size, at the cost of some interactivity.

## How to use React Server Components

To use React Server Components, you will need to use a framework that supports them, such as Next.js. The latest version of NextJS 13.4 uses RCS by default. You can then write components that can be rendered on both the server and the client. When the component is rendered on the server, it will return HTML that can be sent to the client. When the component is hydrated on the client, it will become interactive and dynamic.

To render a server component from your app, you simply import and render it like a normal component:

```js
// components/ServerComponent.jsx
import React from "react";
import db from "db";
import User from "../models/UserModel";
import AddNewUser from "./AddNewUser";
import UserList from "./UserList";

export default aync function MyServerComponent() {
  const userList = await db.users.getAll();

  const addUserToDB = await (data) => {
    const newUser = new User(data);
    db.users.push(newUser);
  }

  return (
    <>
    <AddNewUser addUserToDB={addUserToDB}/>
    <UserList data={userList}/>
  )
};
```

Here we are fetching data from the database directly from the server component. This avoids the round-trip delay of making an API call from the client.

```js
"use client";

import React, { useState } from "react";

const AddNewUser = ({ addUserToDB }) => {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    addUserToDB(name, email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />

      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />

      <button type="submit">Add User</button>
    </form>
  );
};
export default AddNewUser;
```

Any component that starts with `"use client"` is considered a client component and will be rendered on the client. All other components are server components and will be rendered on the server.
Here `AddNewUser` is a client component since it starts with `"use client"`. `MyServerComponent` and `UserList` do not have the directive, so they are server components.

When this component is rendered, `MyServerComponent` will run on the server and output HTML. This HTML will include the rendered result of `<AddNewUser />`. Then when the client receives this HTML, `AddNewUser` will hydrate and run on the client, gaining interactivity.

### Things to note!

- You can import Client Components inside Server Components.
- You cannot import Server Components inside Client Components.
- You can pass a Server Component as a child prop to a Client Component inside Server Component.

## What can React Server Components NOT do?

- RCS cannot use hooks provided by React like `useState`, `useReducer`, `useEffect` and so on, as they are rendered on the server.
- RCS cannot use any utility functions that depend on browser-only APIs (ex: Local Storage)
- RCS cannot be used when components need to have any sort of interactivity. This is where Client Component is used.

## Conclusion

React Server Component is a new and exciting way to build modern, efficient, and scalable applications. They allow developers to render parts of their application on the server while maintaining the interactivity of a client-side app. Although it is still an experimental feature, RCS has a lot of potential and brilliant features that will undoubtedly improve the way modern apps will be built in the future, such as zero bundle size, faster performance, better SEO, and more flexible architecture. It is important to note that React Server Components are still under development and not recommended for production use yet. However, as developers, it is important to stay up-to-date with the latest features introduced to deliver the best results, and React Server Components are worth exploring 💪

I hope you were able to take away something new and useful from this article! If you did, please drop a like on this post. 🙂

You can connect with me on [Twitter](https://twitter.com/supminn), [LinkedIn](https://linkedin.com/in/supminn), and [GitHub](https://github.com/supminn) ✨

Peace ✌

### References

- [Talk by Tejas Kumar](https://youtu.be/rHSVyfDity0?t=1801)
- [Talk by Tapas Adhikary](https://youtu.be/w1L1xRZdLTU?t=5914)