开源日报每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。

2024年1月26日,开源日报第1086期:
今日推荐开源项目:《react-testing-library》
今日推荐英文原文:《It’s 2024, you should be using React Server Components already》


开源项目

今日推荐开源项目:《react-testing-library》传送门:项目链接

推荐理由: 🐐 简单而完整的React DOM测试工具,鼓励良好的测试实践

网站直达:testing-library.com/react


英文原文

今日推荐英文原文:It’s 2024, you should be using React Server Components already

推荐理由:React 服务器组件(RSC)是 Next 和 React 的不太受欢迎的特性,但有三个原因应该在所有项目中使用它们:1. 数据获取更快且更简便;2. 更快的 UI 和更好的用户体验;3. UI 代码更简单


It’s 2024, you should be using React Server Components already

3 reasons why you should actually use RSC in all your projects

Let’s face it, React Server Components aren’t the most liked feature of Next or React. Tons of devs have actually mentally blocked them and decided to pretend they don’t exist by adding use client on top of all their components.

But that’s not only wrong, they’re missing out on a lot of benefits.

In this article I’m going to try and convince you to start using them, so get started.

How do React Server Components work?

To understand the benefits, you first have to understand how these “new” components work.

If you’ve always been a front-end developer, this might actually be the missing piece you needed, so pay attention.

RSC are executed on the server (hence the “server” part of their name). But what does that mean exactly?

It means the framework (let’s say NextJS) will do the following:

  1. It will figure out which components inside the page (including the page actually) are indeed, server components.
  2. For each of them, it will load a server version of React and it will execute them.
  3. Each of these components will output an HTML as a result, and that HTML will take its place inside the bundle that gets shipped to the browser.

The bundle is called React Server Component Payload and inside it, the browser will find:

  • The actual HTML resulted from executing each RSC.
  • Placeholders inside the HTML for client components that need to be hydrated on the browser.
  • Optionally, if there are any props passed from the server components down into the client components, those props will also be inside the payload.

And that’s it.

Is RSC the same as SSR?

This is also a very common question I see being asked around. And I understand the confusion, but no, RSC and SSR are not the same thing.

While SSR (Server-side Rendering) is focused on rendering the entire application on the server and then sending that to the client where hydration happens, RSC focus only on single components. They optimize the rendering process, yes, but at a more granular level.

So now let’s continue with the “why you should use RSC”.

Reason #1: Performing data fetching is faster and easier

Have you ever had to do data-fetching from a React component?

It usually goes like this:

  1. You write your data-fetching logic to directly query the data source if you can (say an external API).
  2. Or you create an internal endpoint on the server side that actually queries the data source (say a database or an external API) and you write your data-fetching logic to hit your internal endpoint.

If you go with #1, the drawbacks are:

  • You might run into CORS problems, given how you’re querying an external API from the browser.
  • You can’t query certain data sources like a database or read a file from disc.
  • You expose the data-fetching logic to the user, potentially divulging code and logic that shouldn’t be seen by end-users (or potential attackers).
  • You’re coupling a lot of the error-handling logic associated with the source of the data with your UI component.

If, instead, you decide to go with option #2, while it’s true that you solve the security aspects of it, and you’re no longer coupling data-fetching error-handling logic to your UI component, you still have to go through the process of writing extra code to create the internal API endpoint.

What if you could have the best of both worlds though? That’s where RSC come into play!

With a React Server Component you can write a component like this:

async function getUserData(){
  //your data fetching logic goes here...
}

async function MyComponent() {

   let data = await getUserData()

   if(!data) {
    return (<div className="error-msg">User not found!</div>)
   } 

   return (
    <div>
       {data.username}
       <DeleteUserButton id={data.id} />
    </div>
   )
}

So, what do we have there? Let’s break it up:

  • We have a component that’s not using any interactive code (no DOM API, no event handlers, no browser API, etc).
  • We have a component that’s not using side effects or state (no useEffect nor useState hooks called).
  • We have a component that’s simply calling a regular function to get some data, and then it’s displaying that data using simple HTML tags.
  • We also have a component that checks for lack of results and simply returns a different HTML.
  • And finally, we have a call to another component called DeleteUserButton that will have event handlers (like an onClick handler) which makes it a client component.

Our server component ended up being simpler than the alternatives we covered because:

  • We didn’t have to create a brand-new internal API endpoint.
  • We didn’t have to couple error-handling logic to a UI component (this is a backend component).
  • We’re not in any danger of encountering any CORS issues with this method.
  • And you can literally query any data source from the getUserData function. Whether it’s a database, an external API or a local text file, you can get that data from wherever you want.

So all in all, a big win so far, but let’s keep going!

Reason #2: Faster UI and better UX

First the disclaimer: this only works if you do things “right”, if you still mess up, just by using RSC you’re not going to get better performance than a well-crafted UI using client components.

With that out of the way, let’s understand what this reason means.

Remember, RSC render on the server, so the first thing we notice is that the browser doesn’t have to do any work to render that part of the DOM. Yes, it has to add those nodes into the overall tree once it receives them from the server, but there is no JavaScript involved to parse code, create HTML elements on the fly and only then update the DOM.

This model allows you to offload the processing power required to render your code to the server. This is especially useful for very complex applications that can turn most of their components into server components.

Another added benefit from the extra work you’re no longer doing on the browser, is that the UI can load faster and start showing information to the end user sooner. This in turn can be seen as an improvement to the UX of your app. Your users suddenly have to wait less time until the first contentful paint, which happens when your browser starts showing anything meaningful to the user.

Reason #3: Simpler UI code

Another very valid reason to start using RSC is to simplify your client component’s logic.

In other words, now you can stop considering your client components as the only place where you should store your UI business logic.

Now instead, you can offload a lot of the “heavy lifting” (like data fetching and data processing) to RSC and let the client components only handle the actual representation (the UI).

This will help you reduce the size of your client components, thus reducing also the size of the bundle that gets shipped to the client whenever a new component needs to be rendered.

With the addition of server components, you’re now able to split the code you had inside your client-only components. You can remove the unnecessary code that was performing non-UI related logic and move it to the server while leaving the rendering part untouched (almost).

And you can even remove entire UI components that don’t need any dynamic behavior (like a footer for instance) and place them on the server to be rendered there. Now suddenly the codebase for your UI is reduced significantly.

That’s also a great win!

To sum it up, react server components are not bad, in fact, they’re great. But they do require a bit of a mindset change at first, especially so if you haven’t done any backend coding in the past.

They bring tons of improvements to your web development workflow, but the main ones I’ve identified are:

  • You’re able to perform easier data-fetching/data processing (and more securely as well).
  • You’re using tools that let you craft better UI/UX for your users with small changes.
  • You’re reducing the complexity of your UI codebase by removing non-UI code from your client components.

If you’d like to know more about React Server Components, I have a fresh new course that teaches you how to use RSC and client components to share state between them. You might want to check it out!


下载开源日报APP:https://openingsource.org/2579/
加入我们:https://openingsource.org/about/join/
关注我们:https://openingsource.org/about/love/