use cache
use cache 指令允許您將路由、React 元件或函式標記為可快取。它可以用於檔案頂部,以指示檔案中所有匯出都應快取,也可以內聯在函式或元件頂部,以快取其返回值。
須知:要快取需要訪問 cookies 或 headers 的使用者特定內容,請參閱
'use cache: private'。
用法
use cache 是一項快取元件功能。要啟用它,請將 cacheComponents 選項新增到您的 next.config.ts 檔案中
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig然後,在檔案、元件或函式級別新增 use cache
// File level
'use cache'
export default async function Page() {
// ...
}
// Component level
export async function MyComponent() {
'use cache'
return <></>
}
// Function level
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}use cache 的工作原理
快取鍵
快取條目的鍵是使用其輸入(包括以下內容)的序列化版本生成的
- 構建 ID(為每次構建生成)
- 函式 ID(函式特有的安全識別符號)
- 可序列化 函式引數(或 props)。
傳遞給快取函式的引數,以及它從父作用域讀取的任何值都會自動成為鍵的一部分。這意味著,只要其輸入相同,相同的快取條目將被重用。
不可序列化的引數
任何不可序列化的引數、props 或閉包值都將在快取函式內部轉換為引用,並且只能透過,不能檢查或修改。這些不可序列化值將在請求時填充,並且不會成為快取鍵的一部分。
例如,快取函式可以接受 JSX 作為 children prop 並返回 <div>{children}</div>,但它無法檢查實際的 children 物件。這允許您將未快取的內容巢狀在快取元件中。
function CachedComponent({ children }: { children: ReactNode }) {
'use cache'
return <div>{children}</div>
}返回值
可快取函式的返回值必須是可序列化的。這確保了快取資料能夠正確儲存和檢索。
在構建時使用 use cache
當在 佈局 或 頁面 頂部使用時,路由段將被預渲染,從而允許它以後進行重新驗證。
這意味著 use cache 不能與 執行時資料(如 cookies 或 headers)一起使用。
注意:如果需要快取依賴於 cookies、headers 或搜尋引數的內容,請改用
'use cache: private'。
在執行時使用 use cache
在伺服器上,單個元件或函式的快取條目將快取在記憶體中。
然後,在客戶端,從伺服器快取返回的任何內容都將儲存在瀏覽器記憶體中,直到會話結束或重新驗證。
在重新驗證期間
預設情況下,use cache 的伺服器端重新驗證週期為 15 分鐘。雖然此週期可能適用於不需要頻繁更新的內容,但您可以使用 cacheLife 和 cacheTag API 來配置何時應重新驗證單個快取條目。
這兩個 API 都整合在客戶端和伺服器快取層中,這意味著您可以在一個地方配置快取語義,並將其應用到所有地方。
有關更多資訊,請參閱 cacheLife 和 cacheTag API 文件。
示例
使用 use cache 快取整個路由
要預渲染整個路由,請將 use cache 新增到 layout 和 page 檔案的頂部。這些段中的每一個都被視為應用程式中的獨立入口點,並將獨立快取。
'use cache'
export default function Layout({ children }: { children: ReactNode }) {
return <div>{children}</div>
}在 page 檔案中匯入和巢狀的任何元件都是與 page 關聯的快取輸出的一部分。
'use cache'
async function Users() {
const users = await fetch('/api/users')
// loop through users
}
export default function Page() {
return (
<main>
<Users />
</main>
)
}須知:
- 如果
use cache僅新增到layout或page,則只有該路由段及其匯入的任何元件將被快取。- 如果路由中任何巢狀的子元件使用 動態 API,則該路由將選擇退出預渲染。
使用 use cache 快取元件的輸出
您可以在元件級別使用 use cache 來快取該元件中執行的任何 fetches 或計算。只要序列化的 props 在每個例項中產生相同的值,快取條目就會被重用。
export async function Bookings({ type = 'haircut' }: BookingsProps) {
'use cache'
async function getBookingsData() {
const data = await fetch(`/api/bookings?type=${encodeURIComponent(type)}`)
return data
}
return //...
}
interface BookingsProps {
type: string
}使用 use cache 快取函式輸出
由於您可以將 use cache 新增到任何非同步函式,因此您不僅限於快取元件或路由。您可能希望快取網路請求、資料庫查詢或緩慢的計算。
export async function getData() {
'use cache'
const data = await fetch('/api/data')
return data
}交錯
在 React 中,使用 children 或 slot 的組合是構建靈活元件的眾所周知的模式。當使用 use cache 時,您可以繼續以這種方式組合您的 UI。作為 children 或其他組合 slot 包含在返回的 JSX 中的任何內容都將透過快取元件傳遞,而不會影響其快取條目。
只要您不直接在可快取函式體內部引用任何 JSX slot,它們在返回輸出中的存在就不會影響快取條目。
export default async function Page() {
const uncachedData = await getData()
return (
// Pass compositional slots as props, e.g. header and children
<CacheComponent header={<h1>Home</h1>}>
{/* DynamicComponent is provided as the children slot */}
<DynamicComponent data={uncachedData} />
</CacheComponent>
)
}
async function CacheComponent({
header, // header: a compositional slot, injected as a prop
children, // children: another slot for nested composition
}: {
header: ReactNode
children: ReactNode
}) {
'use cache'
const cachedData = await fetch('/api/cached-data')
return (
<div>
{header}
<PrerenderedComponent data={cachedData} />
{children}
</div>
)
}您還可以將伺服器操作透過快取元件傳遞給客戶端元件,而無需在可快取函式內部呼叫它們。
import ClientComponent from './ClientComponent'
export default async function Page() {
const performUpdate = async () => {
'use server'
// Perform some server-side update
await db.update(...)
}
return <CacheComponent performUpdate={performUpdate} />
}
async function CachedComponent({
performUpdate,
}: {
performUpdate: () => Promise<void>
}) {
'use cache'
// Do not call performUpdate here
return <ClientComponent action={performUpdate} />
}'use client'
export default function ClientComponent({
action,
}: {
action: () => Promise<void>
}) {
return <button onClick={action}>Update</button>
}平臺支援
| 部署選項 | 支援 |
|---|---|
| Node.js 伺服器 | 是 |
| Docker 容器 | 是 |
| 靜態匯出 | 否 |
| 介面卡 | 平臺特定 |
瞭解如何配置快取,當自託管 Next.js 時。
版本歷史
| 版本 | 更改 |
|---|---|
v16.0.0 | "use cache" 已透過快取元件功能啟用。 |
v15.0.0 | "use cache" 作為實驗性功能推出。 |
相關
use cache: private
cacheComponents
cacheLife
cacheTag
cacheLife
revalidateTag
這有幫助嗎?