Next.js 中 RSC 的渲染策略


前言

Server Components 的组件运行在服务端,但是渲染的方式三种。

Static Rendering (默认方式)

routes are rendered at build time, or in the background after data revalidation.

在构建时候把请求的数据做了缓存,方便后续优先使用。 也可以设置缓存的时间,过期后重新验证,重新验证就会正式发起请求了。

触发的时机:

  • 构建的时候, build time
  • 缓存重新验证的时候, revalidation

适用的场景:

  • 组件没有依赖的数据请求, 做静态渲染的
  • 在构建阶段就能确定数据信息的, 没有用户特定数据的,比如做 blog 的, 或者静态一点的产品页面
  • 首次渲染相当于直出,更加方便缓存和 SEO, 减少服务端压力
  • next.js 中数据请求,如果没有额外设置, 都会被当作 static

Dynamic Rendering

rendered for each user at request time.

每次都是请求的时候渲染。 要想让页面保持 dynamic, nextjs 的策略:

Streaming

enables you to progressively render UI from the server.

Routing: Loading UI and Streaming | Next.js

App Route 默认的渲染方式,有点当年 FB 的 bigPipe 的架构感觉。

利用 React Suspense 实现 Streaming 的渲染方式。支持 node.jsedge 环境。