Understanding React Server Component
Tags: react, nextjs, typescript, beginners
Published: 2024-05-16 03:00:00

## Introduction

As most of us already know, **React** enables us to break down interfaces into independent parts called Components, facilitating reuse and customization. Currently, **React** Components are divided into two main types:

- **Client Components**: widely used in **Client Side Rendering (CSR)** applications.
- **Server Components**: a new type of component that renders on the server side before being sent to the client (browser).
 At first glance, it may seem similar to **Server Side Rendering (SSR)** which has been used for a while, but in reality, these two concepts have certain differences.

## The Difference of RSC (React Server Component)

1. **Ease of development**: **React Server Component** allows easy direct connection to server-side resources such as databases or internal services, streamlining development processes.
2. **Improved performance**: By reducing latency in communication between client and server, **React Server Component** enhances overall application performance.
3. **Reduced source code size**: Libraries utilized only on the server side need not be transmitted to the client, resulting in a lighter source code footprint.
4. Additionally, **Server Components** automatically split the source code into smaller parts, allowing clients to load only necessary sections, thus optimizing performance. This means we no longer need to use techniques like lazy loading as previously required.

```tsx
const Component = React.lazy(() => import('./component'))
```

Just import the components directly that we need to use:
```ts
import Component from './server-component'
```

## Comparing Server Side Rendering with React Server Component

- In both Server **Side Rendering (SSR)** and **Server Component**, rendering occurs on the server side. However, **Server Side Rendering** only returns raw HTML upon initial page load. On the other hand, **Server Component** is treated as an actual component, meaning we can define multiple **Server Components**, use them in various places, and reuse them multiple times.
- With **Server Component**, the result received from the server is merged with the current interface by **React** to create a new interface.

## Limitations of Server Component

- Since **Server Component** is created on the server side, it cannot be used with web browser **APIs** like accessing **_window_** or **_document_** variables.
- Also, **React APIs** such as **useState**, **useContext**, **useEffect**, etc., cannot be used, resulting in **Server Component** not supporting user-interactable events in the application.

## Example Usage

Here's a simple example using **Server Component** to load data, simultaneously with **Client Component**. Note that we'll use **Next**, and the example will be defined in the app directory.

First, create a file **_app/demo/Todo.tsx_**.

```tsx
import {ResTodo} from './type'

// React Server Components
export default function Index({data}: {data: ResTodo}) {
  return (
    <div>
      <ol className="pl-10 list-decimal">
        {data.todos.map(todo => (
          <li key={todo.id}>{todo.todo}</li>
        ))}
      </ol>
    </div>
  )
}
```

Next, create a file **_app/demo/AddTodo.tsx_**.
```tsx
'use client'

import {useState} from 'react'
import {addTodo} from './service'

// Client Components
export default function Index() {
  const onAddTodo = (): void => {
    addTodo({todo})
  }
  return (
    <div>
      <Input placeholder="Todo title" onChange={}></Input>
      <Button onClick={onAddTodo}>Add</Button>
    </div>
  )
}
```

Finally, create a file **_app/demo/page.tsx_**, where the **_getTodoData_** function is used to directly fetch the todo list from the server. We can query the database to fetch the data right here.
```tsx
import {getTodoData} from './service'
import AddTodo from './AddTodo'
import Todos from './Todos'

// React Server Components
export default async function Index() {
  const data = await getTodoData()
  return (
    <div>
      <AddTodo />
      <Todos data={data} />
    </div>
  )
}
```

When you successfully start the application, in the Sources tab, you'll only see the **_AddTodo.tsx_** file (**_Client Component_**) in the client-side source code, without the **_Todo.tsx_** file (**_Server Component_**).

![Bundle response of client side](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yke7x1qzril5fqhxcfg9.png)

## In Summary

- **React Server Component** is a new feature supported by **Next** from version **13**, currently still in development and testing phase. You should consider carefully if you want to use it in a production environment.
- However, once the feature becomes stable, it promises to be a significant development step for React, providing better support for **SSR** and optimizing **React** applications further.

**_If you have any suggestions or questions regarding the content of the article, please don't hesitate to leave a comment below!_**

**_If you found this content helpful, please visit [the original article on my blog](https://howtodevez.blogspot.com/2024/03/understanding-react-server-component.html) to support the author and explore more interesting content._**🙏🙏

<a href="https://howtodevez.blogspot.com/2024/03/sitemap.html" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Blogger-FF5722?style=for-the-badge&logo=blogger&logoColor=white" width="36" height="36" alt="Blogspot" /></a><a href="https://dev.to/chauhoangminhnguyen" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/dev.to-0A0A0A?style=for-the-badge&logo=dev.to&logoColor=white" width="36" height="36" alt="Dev.to" /></a><a href="https://www.facebook.com/profile.php?id=61557154776384" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Facebook-1877F2?style=for-the-badge&logo=facebook&logoColor=white" width="36" height="36" alt="Facebook" /></a><a href="https://x.com/DavidNguyenSE" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/X-000000?style=for-the-badge&logo=x&logoColor=white" width="36" height="36" alt="X" /></a>