Next.js 中数据请求


前言

扩展 native 的 fetch

allow you to configure the caching and revalidating behavior for each fetch request on the server.

可使用的地方:

  • Server Components
  • route handlers
  • Server Actions

React 端自动 memoize 了请求

React extends fetch to automatically memoize fetch requests while rendering a React component tree.

Building Your Application: Caching | Next.js

在组件发送大量请求的时候, 自动做优化,把相同的合并成一个,使用对应的响应。这是在相当于 Batch 的阶段处理的:

How Request Memoization Works

Caching

By default, Next.js automatically caches the returned values of fetch in the Data Cache on the server.

数据缓存的策略。默认是 force-cache. 内置了数据缓存机制,Building Your Application: Caching | Next.js, 缓存架构如下:

How Data Cache Works

哪些方法会导致 dynamic rendered?

如果使用了 cookiesheaders 方法。

Revalidating

重新验证是指清除数据缓存并重新获取最新数据的过程。当您的数据发生变化且希望确保显示最新信息时,使用此功能十分方便。

技术总结

Next.js 官方给了最佳实践: Data Fetching: Data Fetching Patterns and Best Practices | Next.js

app route 的模式下,请求优先放在服务端,配合 Streaming 的模式, 可以做到高性能,并发的渲染。并且 next.js 在服务端, 扩展了很多 fetch 的能力,比如 memoizecache, 自带为我们带来了很多性能优化。