React Server Components(RSC)和服务器端渲染(SSR)之间的区别是什么?

huangapple go评论106阅读模式
英文:

What is the difference between React Server Components (RSC) and Server Side Rendering (SSR)?

问题

React 18引入了RSC。我想知道它与NextJS中的SSR有什么不同。

英文:

So with React 18 came RSC. I'd like to how is it different from SSR we have in NextJS.

答案1

得分: 10

在这两种情况下,React JavaScript 代码由 Node.js(或 Deno,或者您使用的其他工具)执行。但它们生成不同的内容。

SSR

服务器端渲染是指当 React 使用 ReactDom 的 renderToString() 方法将组件呈现为 HTML 字符串,并将该 HTML 字符串发送给客户端时,与任何服务器发送静态 HTML 一样。

然后,通常在 SSR 设置中,React 在客户端上重新运行,对相同呈现的 HTML 运行,并执行诸如连接点击处理程序和添加交互性等操作。这需要服务器和客户端具有相同的数据来进行呈现。这是通过将服务器上的数据序列化为客户端上的 <script> 标签,其中包含表示 React 状态的对象来完成的,然后 React 在客户端上使用相同的状态进行“水合”。如果客户端具有不同的数据,它将生成不同的 DOM 树,并覆盖服务器创建的内容,这会破坏 SSR 的目的。

在服务器和客户端都使用 React,初始页面加载可以是 SSR,然后后续页面加载可以是客户端端渲染。对于初始页面加载,SSR 比客户端端渲染要快得多,一旦下载了所有 JavaScript 资源,客户端端渲染就更快。这就是在使用 SSR 时 Next.js 默认采用的策略。

服务器组件

服务器组件不会呈现为 HTML 字符串。

React 的“组件”是返回 React “元素”的函数或类。React 的“元素”是要呈现的树的对象表示。在正常操作模式下,ReactDOM 获取这些元素对象并将它们呈现到 DOM 中。

服务器组件将 React “元素”返回到客户端。在服务器上,组件运行并生成元素,然后将这些元素传递给客户端(基本上是作为 JSON)。然后,这些“元素”在客户端上呈现,并放入 DOM 中。

英文:

In both cases, React Javascript code is executed by Node.js (or Deno, or whatever you're using). But they generate different things.

SSR

Server-side rendering is when React renders components to a string of HTML using ReactDom's renderToString() method, and sends that HTML string to the client, the same as any server sending static HTML.

Then, usually with SSR setups, React re-runs on the client side, running over the same rendered HTML, and does things like wire up click handlers and add interactivity. This requires that the server and the client have the same data to render. This is done by serializing the data on the server into a &lt;script&gt; tag on the client with the object representing the React state, and React "hydrates" on the client with that same state. If the client has different data, it will produce a different DOM tree, and overwrite what the server created, which defeats the purpose of SSR.

With React on both the server and client, the initial page load can be SSR, and then subsequent page loads can be client side. SSR is much faster than client side rendering for initial page loads, and then client side is faster once all the Javascript resources are downloaded. This strategy is what Next.js does by default when you use SSR.

Server Components

Server components don't render to an HTML string.

A React "component" is a function or a class that returns React "elements." A React "element" is the object representation of the tree to render. In normal operation mode, ReactDOM takes these element objects and renders them to the DOM.

Server components return react elements to the client side. On the server, the components run, and generate elements, which are passed to the client (basically as JSON). These elements are then rendered on the client and put into the DOM.

答案2

得分: 1

React Server Components 是一种新型组件,仅可在服务器上呈现并作为 HTML 发送到客户端。

来自 NextJS 的一位创建者(Vercel 团队成员)介绍了 RSC 和 SSR 的主要区别,RSC 仍然保留客户端中任何组件的状态,但 RSC 不能像 SSR 那样进行"水合"(这就是为什么我们不能在服务器组件上使用 React hook 或事件监听器的原因)。

例如,我们有一个父组件(服务器组件),里面有一个用于搜索的输入框(客户端组件)。然后,我们在该输入框上附加了 onChange 事件,现在每当我们键入内容时,整个父组件都会重新呈现。服务器组件将帮助我们在客户端保留旧状态,这是我们在输入框中输入的数据,而 SSR 将使整个内容刷新。

(在视频中跳转到演示部分以进行演示)

https://www.youtube.com/watch?v=DuSa5E-GgwU

英文:

React Server Components are a new type of component that can be rendered only on the server and sent to the client as HTML.

From one of the creators of NextJS (in the Vercel team), the major difference between RSC and SSR is that RSC still keeps the state of any components in the client and RSC can not be hydrated like SSR (that's why we can not use React hook or event listener on server component).

For example, we have a parent component (server component) and inside we have an input (client component) for searching. We then attach onChange event on that input and now whenever we type something, we make the whole parent component re-rendered. Server component will help us keep the old state on the client side which is the data that we typed in input element while SSR will make the whole thing refresh.

(jump to the demo section in the video for demonstration)

https://www.youtube.com/watch?v=DuSa5E-GgwU

答案3

得分: 1

SSR 是在服务器上运行代码。

Next.js 曾经通过使用 getServerSideProps(文档)来实现这一点。

function Page({ data }) {
  // 渲染数据...
}
 
// 这在每个请求时都会被调用
export async function getServerSideProps() {
  // 从外部 API 获取数据
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  // 通过 props 将数据传递给页面
  return { props: { data } }
}
 
export default Page

通过 React 服务器组件功能和随后的 Next.js 13,Next.js 开发人员可以使用这一功能,而不是 getServerSideProps(文档)。

async function getData() {
  const res = await fetch('https://api.example.com/...');
  // 返回值不会被序列化
  // 你可以返回 Date、Map、Set 等等
  return res.json();
}
 
// 这是一个异步的服务器组件
export default async function Page() {
  const data = await getData();
 
  return <main>{/* ... */}</main>;
}
英文:

SSR is to run code on the server.

Nextjs used to allow us to do so by using getServerSideProps (doc) .

function Page({ data }) {
  // Render data...
}
 
// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  // Pass data to the page via props
  return { props: { data } }
}
 
export default Page

With React server component feature and following nextjs 13 ,nextjs developers can use this feature instead of getServerSideProp . (doc) .

async function getData() {
  const res = await fetch(&#39;https://api.example.com/...&#39;);
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
  return res.json();
}
 
// This is an async Server Component
export default async function Page() {
  const data = await getData();
 
  return &lt;main&gt;{/* ... */}&lt;/main&gt;;
}

huangapple
  • 本文由 发表于 2023年5月25日 00:57:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定