Blogs
Hiểu về React Server Components

Hiểu về React Server Components

Cách RSC cải thiện hiệu suất và giảm JavaScript phía client

Giới thiệu

React Server Components (RSC) là một tính năng mang tính đột phá giúp cải thiện hiệu suất bằng cách giảm lượng JavaScript tải xuống trình duyệt. Khác với các Component truyền thống, RSC chạy hoàn toàn trên server, giúp tối ưu hóa việc lấy dữ liệu và giảm tải cho frontend.

Bài viết này sẽ giúp bạn hiểu rõ về React Server Components, lợi ích của chúng, sự khác biệt so với Client Components truyền thống và cách sử dụng trong Next.js.

React Server Components là gì?

Thông thường, React render component trên trình duyệt bằng JavaScript. Nhưng với RSC, một số component được render trên server và gửi HTML về client, giúp giảm đáng kể kích thước bundle JavaScript.

Cách RSC hoạt động

RSC chạy trên server, thực hiện logic và gửi kết quả đã được serialize về client. Khác với Server-Side Rendering (SSR) gửi nguyên trang HTML đã render, RSC cho phép render từng phần và truyền dần xuống client.

Điều này giúp RSC có thể truy vấn dữ liệu trực tiếp từ database hoặc API mà không cần thêm request từ client, giảm độ trễ và tối ưu hiệu suất.

Lợi ích của RSC

  • Giảm JavaScript tải xuống client: Không gửi JavaScript thừa về trình duyệt, giúp trang tải nhanh hơn.
  • Cải thiện SEO: Nội dung render sẵn trên server giúp công cụ tìm kiếm dễ dàng thu thập dữ liệu.
  • Tối ưu hóa việc lấy dữ liệu: Fetch dữ liệu trực tiếp trên server, không cần gọi API từ client.
  • Tích hợp dễ dàng: Có thể sử dụng cùng với Client Components khi cần.
  • Tăng tốc độ tải trang: Gửi HTML đã render sẵn giúp người dùng thấy nội dung ngay lập tức.
  • Giảm tải bộ nhớ trình duyệt: Trạng thái được xử lý trên server, giúp trình duyệt hoạt động mượt mà hơn.

Sử dụng React Server Components trong Next.js

Next.js 13+ hỗ trợ hoàn toàn RSC. Mặc định, tất cả component trong thư mục app/ của Next.js đều là Server Components, trừ khi bạn chỉ định là Client Component.

Ví dụ: Một Server Component đơn giản

// app/components/PostList.tsx (Mặc định là Server Component) import { getPosts } from '@/lib/api'; export default async function PostList() { const posts = await getPosts(); return ( <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> ); }

Khi nào cần dùng Client Component?

Một số component vẫn cần chạy trên client, như những component sử dụng useState, useEffect hoặc có event listener. Để chỉ định một component là Client Component, thêm 'use client' ở đầu file:

// app/components/Button.tsx 'use client'; import { useState } from 'react'; export default function Button() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>Click {count}</button>; }

React Server Components vs. Server-Side Rendering

Nhiều người nhầm lẫn giữa React Server Components (RSC)Server-Side Rendering (SSR). Dưới đây là bảng so sánh:

Đặc điểmReact Server Components (RSC)Server-Side Rendering (SSR)
Chạy trênServerServer
Gửi JavaScript xuống clientKhông
Quản lý stateXử lý trên serverCần hydration trên client
Hỗ trợ SEO
Lấy dữ liệuFetch trực tiếp trên serverGọi API từ client
Ứng dụng phù hợpGiảm tải JS, tối ưu hiệu suấtRender trang động, cập nhật dữ liệu theo thời gian thực

Khi nào nên sử dụng RSC?

React Server Components phù hợp khi bạn muốn giảm JavaScript chạy trên client. Một số trường hợp sử dụng phổ biến:

  • Trang nội dung tĩnh: Blog, tài liệu, trang tin tức.
  • Ứng dụng dashboard: Lấy dữ liệu lớn trên server mà không ảnh hưởng đến frontend.
  • Website thương mại điện tử: Hiển thị danh sách sản phẩm theo thời gian thực mà không gửi nhiều script xuống client.
  • Ứng dụng streaming: Tải dần nội dung để cải thiện trải nghiệm người dùng.

Tránh lỗi Hydration trong RSC

Khi kết hợp RSC với Client Components, cần chú ý tránh lỗi hydration mismatch, tức là nội dung render trên server khác với nội dung hiển thị trên client. Một số nguyên nhân phổ biến:

  • Không sử dụng giá trị thay đổi theo thời gian như Date.now() hoặc Math.random() trong Server Components.
  • Không render JSX không hợp lệ, chẳng hạn như <div> nằm trong <p>.
  • Không sử dụng các API chỉ chạy trên client, ví dụ window, document, localStorage trong Server Components.
  • Khi cần interactivity, hãy tách component đó thành Client Component bằng cách thêm 'use client'.

Kết luận

React Server Components giúp tăng hiệu suất bằng cách giảm tải JavaScript cho client. Khi kết hợp với Next.js, RSC giúp tối ưu trải nghiệm người dùng bằng cách cải thiện tốc độ tải trang và giảm tải cho trình duyệt.

🚀 Bạn đã sẵn sàng thử RSC chưa? Hãy bắt đầu bằng cách refactor component của bạn để tận dụng tối đa lợi ích của RSC!

Hiểu rõ cách sử dụng RSC sẽ giúp bạn xây dựng ứng dụng React nhanh hơn, nhẹ hơn và dễ bảo trì hơn.

Understanding React Server Components

How RSC improves performance and reduces client-side JavaScript

Introduction

React Server Components (RSC) are a groundbreaking feature that improves performance by reducing the amount of JavaScript sent to the browser. Unlike traditional components, RSCs run entirely on the server, optimizing data fetching and reducing frontend workload.

This article will help you understand React Server Components, their benefits, how they differ from traditional Client Components, and how to use them effectively in Next.js.

What are React Server Components?

Normally, React components are rendered in the browser using JavaScript. With RSC, however, some components are rendered on the server and only the serialized HTML is sent to the client — significantly reducing the bundle size.

How RSC Works

RSCs execute on the server, run logic, and send serialized output to the client. Unlike Server-Side Rendering (SSR), which renders the entire page, RSCs allow partial rendering and progressive streaming to the client.

RSCs can directly access data sources (like databases or APIs) without extra client-side requests, resulting in lower latency and better performance.

Benefits of RSC

  • Reduced JavaScript on client: Less JS sent to the browser means faster page loads.
  • Improved SEO: Content is server-rendered, making it more crawlable.
  • Efficient data fetching: Fetch data directly on the server.
  • Seamless integration: Can be used alongside Client Components when needed.
  • Faster perceived load: HTML is sent progressively, allowing content to appear quickly.
  • Reduced memory usage in browser: Server handles state, keeping the client lightweight.

Using React Server Components in Next.js

Next.js 13+ fully supports RSC. By default, all components inside the app/ directory are Server Components, unless explicitly marked as client components.

Example: A Simple Server Component

// app/components/PostList.tsx (By default, it's a Server Component) import { getPosts } from '@/lib/api'; export default async function PostList() { const posts = await getPosts(); return ( <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> ); }

When to Use Client Components

Some components must run on the client, like those using useState, useEffect, or event listeners. To mark a file as a Client Component, use 'use client' at the top:

// app/components/Button.tsx 'use client'; import { useState } from 'react'; export default function Button() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>Click {count}</button>; }

React Server Components vs. Server-Side Rendering

Many developers confuse React Server Components (RSC) with Server-Side Rendering (SSR). Here's a comparison:

FeatureReact Server Components (RSC)Server-Side Rendering (SSR)
Runs onServerServer
Sends JS to clientNoYes
State managementHandled on the serverRequires hydration on client
SEO supportYesYes
Data fetchingDirectly on serverVia API calls from client
Best use caseJS reduction, performanceDynamic pages, real-time data

When Should You Use RSC?

React Server Components are ideal when your goal is to minimize JS on the client. Common use cases:

  • Static content pages: Blogs, docs, news.
  • Dashboards: Fetch heavy data on the server, leaving the client light.
  • E-commerce websites: Display live product lists without excessive client-side JS.
  • Streaming apps: Progressive loading improves UX.

Avoiding Hydration Issues in RSC

When mixing RSC with Client Components, be careful to avoid hydration mismatches — differences between server-rendered and client-rendered output. Common mistakes include:

  • Using non-deterministic values like Date.now() or Math.random() in server components.
  • Invalid HTML structure, e.g., putting <div> inside <p>.
  • Using client-only APIs, such as window, document, or localStorage inside server components.
  • Needing interactivity? Move that logic into a Client Component using 'use client'.

Conclusion

React Server Components significantly boost performance by offloading logic and rendering to the server. In combination with Next.js, RSCs enhance user experience by reducing page load times and browser workload.

🚀 Ready to try RSC? Start by refactoring components to leverage the full power of server rendering!

Mastering RSC will help you build faster, lighter, and more maintainable React applications.

Tags

Buy Me A Coffee
    ReactJSNextJS