DEV Community

Cover image for Understanding React Server Component
chauhoangminhnguyen
chauhoangminhnguyen

Posted on • Edited on • Originally published at howtodevez.blogspot.com

Understanding React Server Component

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.
const Component = React.lazy(() => import('./component'))
Enter fullscreen mode Exit fullscreen mode

Just import the components directly that we need to use:

import Component from './server-component'
Enter fullscreen mode Exit fullscreen mode

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.

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

Next, create a file app/demo/AddTodo.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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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

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 to support the author and explore more interesting content.🙏🙏

BlogspotDev.toFacebookX

Top comments (0)