Is it better to fetch data once and save it in state or to refetch it with server functions in next js 13?

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

Is it better to fetch data once and save it in state or to refetch it with server functions in next js 13?

问题

我目前正在进行一个Next.js项目,关于数据获取有一个问题。在最新版本的Next.js中,通过服务器组件直接从数据库获取数据的功能已经存在。在较早的Next.js版本中,你会获取数据,然后将其保存到状态中,并在数据更改时本地更新状态。你可能还会使用上下文在组件和页面之间共享数据。我的问题是在性能和代码质量方面,哪种方法更好。此外,在服务器组件中,如何在页面之间共享数据以及在数据更改时如何更新数据?我相信有一个revalidate选项,但我不太确定。

英文:

I am currently working on a next js project, and I have a question about data fetching. In the latest version of next js, there is the ability to fetch data directly from the database through server components. In older versions of next js, you would fetch data and then save it to a state and update the state locally whenever your data changes. You would likely also use a context to share data between components and pages. My question is which method is better in terms of performance and in terms of code quality. Also, in server components how do you share data between pages and how do you update data when it is changed? I believe there is a revalidate option, but I am not sure about that.

答案1

得分: 1

Fetching is better, but fetching many times makes the server busy, so you can use caching solution.

You can create a page with NO SSR, instead you can fetch data with SWR.
It's clear if you have to get data from your API, you have to create another page in /api direction to response the requests from client.

This lib created by NextJS developers. It will cache fetched data and prevents your server from many requests.
You can install and read documents in here:
https://swr.vercel.app/

英文:

Fetching is better, but fetching many times makes the server busy, so you can use caching solution.

You can create a page with NO SSR, instead you can fetch data with SWR.
It's clear if you have to get data from your API, you have to create another page in /api direction to response the requests from client.

This lib created by NextJS developers. It will cache fetched data and prevents your server from many requests.
You can install and read documents in here:
https://swr.vercel.app/

huangapple
  • 本文由 发表于 2023年5月11日 18:06:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226446.html
匿名

发表评论

匿名网友

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

确定