Skip to content

Commit 0842b70

Browse files
authored
docs(blog): update server post (#6394)
1 parent 8a76530 commit 0842b70

File tree

1 file changed

+180
-12
lines changed

1 file changed

+180
-12
lines changed

documentation/blog/2024-01-25-react-server-components.md documentation/blog/2024-10-07-react-server-components.md

+180-12
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@ description: We will discuss what React server components are as well as how to
44
slug: react-server-components
55
authors: peter_osah
66
tags: [react]
7-
image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-07-09-react-server-components/social.png
7+
image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-07-09-react-server-components/social-3.png
88
hide_table_of_contents: false
99
---
1010

11-
**_This article was last updated on January 25, 2024 to add new usecases and clear definition for React Server Components_**
11+
**_This article was last updated on October 07, 2024 to include sections on Hydration, Performance Benefits, and Error Handling for React Server Components._**
1212

1313
## Introduction
1414

@@ -23,9 +23,11 @@ Steps we'll follow:
2323
- [Differences between React server components and client components](#differences-between-react-server-components-and-client-components)
2424
- [Differences between React server components and server-side rendering(SSR) in React](#differences-between-react-server-components-and-server-side-renderingssr-in-react)
2525
- [Using server components in a React application](#using-server-components-in-a-react-application)
26+
- [Error Boundaries in React Server Components](#error-boundaries-in-react-server-components)
2627
- [When to use React server components?](#when-to-use-react-server-components)
2728
- [Using server components in a Next.js application](#using-server-components-in-a-nextjs-application)
2829
- [Pros and Cons of React server components](#pros-and-cons-of-react-server-components)
30+
- [Bonus: Hydration and React Server Components](#bonus-hydration-and-react-server-components)
2931

3032
## What are React server components?
3133

@@ -207,12 +209,12 @@ const PostEditor = ({ blogPost }) => {
207209

208210
return (
209211
<div>
210-
<div className="md:mx-auto px-6 md:px-0 mt-10 md:w-9/12">
212+
<div className="mt-10 px-6 md:mx-auto md:w-9/12 md:px-0">
211213
<h1 className="my-4 text-center">Create Post</h1>
212214

213215
<form onSubmit={submitPost}>
214216
<div className="mt-8">
215-
<label className="text-white mb-2"> Title </label>
217+
<label className="mb-2 text-white"> Title </label>
216218
<input
217219
type="text"
218220
placeholder=""
@@ -223,18 +225,18 @@ const PostEditor = ({ blogPost }) => {
223225
</div>
224226

225227
<div className="mt-8">
226-
<label className="text-white mb-2">Add your Blog content</label>
228+
<label className="mb-2 text-white">Add your Blog content</label>
227229
<textarea
228230
value={post.content}
229231
required
230232
onChange={(e) => onChange("content", e.target.value)}
231233
></textarea>
232234
</div>
233235

234-
<div className="flex justify-end mt-8">
236+
<div className="mt-8 flex justify-end">
235237
<button
236238
type="submit"
237-
className="px-4 py-4 bg-[#0e9f64] c-white border-radius"
239+
className="c-white border-radius bg-[#0e9f64] px-4 py-4"
238240
>
239241
Create Post
240242
</button>
@@ -285,6 +287,39 @@ const ServerComponent1 = () => {
285287
};
286288
```
287289

290+
## Error Boundaries in React Server Components
291+
292+
Some thoughts concerning error handling in React Server Components, as we work with them quite a bit. Here are some key things to keep in mind:
293+
294+
### Catching Errors on the Server Level
295+
296+
The beauty of it is that in RSCs, we can handle errors on the server before they even reach the client. Great, because at least we can return either the fallback UI or the error message and not affect the client-side code. We just have to make sure to handle API or database failures with aplomb so the user doesn’t see broken components.
297+
For instance, on an RSC, which fetches data from a random API, we can wrap our data fetch inside a try-catch block:
298+
299+
```tsx
300+
const BlogPost = async ({ id }) => {
301+
try {
302+
const post = await db.posts.get(id);
303+
return <div>{post.title}</div>;
304+
} catch (error) {
305+
console.error("Error fetching post:", error);
306+
return <div>Something went wrong. Please try again later.</div>;
307+
}
308+
};
309+
```
310+
311+
#### User Feedback
312+
313+
It is always good to return users clear feedback when something goes wrong. Even though things are handled on the server side by the RSCs, we should always return a friendly message on the UI in case of an error; that way they know something went wrong, and we are working on it.
314+
315+
#### Logging and Monitoring
316+
317+
And, of course, log the errors server-side! Since RSCs run on the server, it’s a heck of a lot easier to track errors and performance metrics. We can plug in logging services like Sentry to automatically detect and report issues to us. That gives us far better insight into what’s actually going wrong and helps us fix issues much quicker.
318+
319+
#### Fallbacks for Non-Critical Data
320+
321+
For non-vital areas of the UI, we can render fallback content or even loading states. If the data is not important, instead of rendering an error, we could always render a default component until the issue is resolved. Here, at least the app is not fully broken, and users can still interact with it for core functionalities.
322+
288323
## When to use React server components?
289324

290325
- **Faster Initial Load Times:** React Server Components significantly reduce web app loading times, improving the user experience.
@@ -349,12 +384,12 @@ const PostEditor = ({ blogPost }) => {
349384

350385
return (
351386
<div>
352-
<div className="md:mx-auto px-6 md:px-0 mt-10 md:w-9/12">
387+
<div className="mt-10 px-6 md:mx-auto md:w-9/12 md:px-0">
353388
<h1 className="my-4 text-center">Create Post</h1>
354389

355390
<form onSubmit={submitPost}>
356391
<div className="mt-8">
357-
<label className="text-white mb-2"> Title </label>
392+
<label className="mb-2 text-white"> Title </label>
358393
<input
359394
type="text"
360395
placeholder=""
@@ -365,18 +400,18 @@ const PostEditor = ({ blogPost }) => {
365400
</div>
366401

367402
<div className="mt-8">
368-
<label className="text-white mb-2">Add your Blog content</label>
403+
<label className="mb-2 text-white">Add your Blog content</label>
369404
<textarea
370405
value={post.content}
371406
required
372407
onChange={(e) => onChange("content", e.target.value)}
373408
></textarea>
374409
</div>
375410

376-
<div className="flex justify-end mt-8">
411+
<div className="mt-8 flex justify-end">
377412
<button
378413
type="submit"
379-
className="px-4 py-4 bg-[#0e9f64] c-white border-radius"
414+
className="c-white border-radius bg-[#0e9f64] px-4 py-4"
380415
>
381416
Create Post
382417
</button>
@@ -407,6 +442,139 @@ In this section, we will explore the pros and cons of React Server Components.
407442
- You can only use React Server components with meta React frameworks. At the moment, you can only use it with Next.js. You can't use it with vanilla React.
408443
- RSCs can be complex, unintuitive and difficult to get right. RSCs introduce a new mental model. The shift in paradigm comes with significant learning overhead.
409444

445+
## Bonus: Hydration and React Server Components
446+
447+
In React, hydration means attaching React’s event listeners to already rendered HTML on the client side in order to make it interactive. React Server Components (RSCs) are rendered only on the server, so they don’t need hydration. Client components, however, require hydration since they handle interactions such as clicks and inputs.
448+
449+
### Basic Hydration Setup
450+
451+
For interactive components, they must be client components. React will hydrate them once the page loads. Server components, on the other hand, generate only HTML and don’t have any interactive behavior, so they aren’t hydrated.
452+
453+
Here’s an example:
454+
455+
```tsx
456+
// ServerComponent.tsx - This won't be hydrated
457+
export const ServerComponent = async () => {
458+
const data = await fetchSomeData();
459+
460+
return (
461+
<div>
462+
<h1>{data.title}</h1>
463+
<p>{data.description}</p>
464+
</div>
465+
);
466+
};
467+
```
468+
469+
This ServerComponent is rendered on the server, and no JavaScript is sent to the client for this component. It outputs static HTML and is never hydrated.
470+
471+
```tsx
472+
// ClientComponent.tsx - This will be hydrated
473+
"use client"; // Flagging it as a client component
474+
475+
import { useState } from "react";
476+
477+
export const ClientComponent = () => {
478+
const [count, setCount] = useState(0);
479+
480+
return (
481+
<div>
482+
<button onClick={() => setCount(count + 1)}>Increment: {count}</button>
483+
</div>
484+
);
485+
};
486+
```
487+
488+
The ClientComponent is marked as ‘use client’, so React will hydrate this component on the client, making it interactive—updating the count when the button is clicked.
489+
490+
### Hydration in Next.js with Server and Client Components
491+
492+
By default, components in a Next.js app are server components, and client components must be explicitly declared. Hydration occurs only for client components. Here’s an example using both server and client components:
493+
494+
```tsx
495+
// app/BlogPage.tsx - Next.js Example using both Server and Client components
496+
497+
import { ServerComponent } from "./ServerComponent";
498+
import { ClientComponent } from "./ClientComponent";
499+
500+
export default function BlogPage() {
501+
return (
502+
<div>
503+
{/* ServerComponent will be rendered as static HTML on the server */}
504+
<ServerComponent />
505+
506+
{/* ClientComponent will be hydrated on the client for interactivity */}
507+
<ClientComponent />
508+
</div>
509+
);
510+
}
511+
```
512+
513+
In this example:
514+
515+
ServerComponent is rendered as static HTML on the server.
516+
ClientComponent is hydrated on the client after the page loads, making the button interactive.
517+
518+
### How Hydration Works: A Deeper Look
519+
520+
React Server Components don’t send any JavaScript to the client. The server provides fully-rendered HTML, and hydration applies only to client components, which handle things like button clicks and form submissions.
521+
522+
Here’s how hydration works for a client component:
523+
524+
- 1. The static HTML for the client component is already rendered on the page.
525+
- 2. After React’s JavaScript bundle is downloaded, React looks for the existing HTML markup and attaches event listeners to the DOM nodes.
526+
- 3. Now, the component becomes interactive.
527+
528+
```tsx
529+
// ClientComponent.tsx
530+
"use client";
531+
532+
import { useState } from "react";
533+
534+
export const Counter = () => {
535+
const [count, setCount] = useState(0);
536+
537+
return (
538+
<div>
539+
<p>Count: {count}</p>
540+
<button onClick={() => setCount(count + 1)}>Increment</button>
541+
</div>
542+
);
543+
};
544+
```
545+
546+
In the example above:
547+
548+
When the page loads, React will hydrate the Counter component, attaching the onClick handler to the button. The button becomes interactive after hydration.
549+
550+
### Why Hydration Is Not Needed for Server Components
551+
552+
Server components are static and don’t include any logic for interactivity. They don’t require hydration because they don’t run on the client. This reduces the amount of JavaScript the client has to download, improving performance.
553+
554+
```tsx
555+
// ServerComponent.tsx - Non-interactive server component
556+
557+
export const StaticContent = async () => {
558+
const data = await fetch("https://api.example.com/data");
559+
const result = await data.json();
560+
561+
return (
562+
<div>
563+
<h1>{result.title}</h1>
564+
<p>{result.description}</p>
565+
</div>
566+
);
567+
};
568+
```
569+
570+
The ServerComponent fetches data and renders it as HTML on the server. It doesn’t include any JavaScript that needs to be sent to the client.
571+
572+
### Improving Performance with Reduced Hydration
573+
574+
One of the key performance benefits of React Server Components is the reduced need for hydration. Since server components don’t include JavaScript, the client has less work to do, and page load times are faster.
575+
576+
To avoid excessive hydration, we should only use client components when necessary (e.g., for interactivity like forms and buttons). Server components should handle static content or non-interactive logic to keep the client bundle small.
577+
410578
## Conclusion.
411579

412580
In this article, we explored React server components and discussed its use and benefits. React server components enable us combine both client-side and server-side rendered components in React applications in a new way. I hope this article convinces you to test out React server components today.

0 commit comments

Comments
 (0)