A React Server Component (RSC) is a new type of React component that executes exclusively on the server (or at build time). Unlike traditional components, their code is never sent to the browser, which significantly reduces the JavaScript bundle size.
Core Concepts
- Zero Bundle Size: Because RSCs stay on the server, the libraries they use (like heavy Markdown parsers or database drivers) are not included in the client-side JavaScript bundle.
- Direct Server Access: They can directly access server-side resources like databases, file systems, or internal microservices without needing an intermediate API layer.
- Async by Nature: RSCs are often functions, allowing you to use standard syntax to fetch data directly inside the component body.
- Stateless on the Client: They do not use client-side features like , , or browser APIs (e.g., , ).
Key Benefits
- Performance: Faster initial page loads and improved Core Web Vitals, such as Largest Contentful Paint (LCP), because less JavaScript needs to be parsed and executed by the browser.
- No Data Waterfalls: By fetching data on the server (closer to the data source), RSCs eliminate the "waterfall" effect where child components must wait for parent components to finish fetching data over the network.
- Security: Sensitive information like API keys or database credentials remains securely on the server and is never exposed to the client.
Difference from Server-Side Rendering (SSR)
While both involve the server, they solve different problems:
- SSR focuses on generating the initial HTML for a fast first view. The entire component tree still hydrates (becomes interactive) on the client, meaning all JavaScript is still sent to the browser.
- RSC allows specific components to remain server-only. They send a serialized React Server Component Payload
(not just HTML) that allows React to merge server-rendered UI into the client-side tree without losing client state.
When to Use Each
| Feature | Server Component (RSC) | Client Component |
| Data Fetching | Yes (Directly from DB/API) | No (Use hooks like ) |
| Interactivity | No (No click handlers) | Yes (onClick, onChange, etc.) |
| State & Lifecycle | No (, ) | Yes |
| Backend Access | Yes (File system, DB) | No |
| Bundle Size | Zero | Contributes to JS bundle |
In modern frameworks like Next.js (App Router), components are Server Components by default. To create a Client Component, you must add the directive at the top of the file.
No comments:
Post a Comment