如何使用 SWR 获取客户端数据
使用 SWR 获取客户端数据,可选择从 Server Component 提供初始数据,并协调服务端和客户端缓存。
使用 SWR 在 Client Component 中获取数据、从 Server Component 提供初始数据,并协调浏览器中的变更操作与缓存的服务端数据。请参阅客户端数据获取以选择适合的模式。
在客户端获取数据#
当初始视图可以等待 hydration 之后的浏览器请求时,SWR 可以完全在浏览器中获取数据。根据加载 UI 应出现的位置,选择内联或 Suspense 加载状态。在这些示例中,query 初始为空,并在 hydration 后根据客户端状态更新。
当组件应自行渲染加载和错误状态时,使用 useSWR。条件式 key 可将请求延迟到交互提供输入之后:
'use client'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
const {
data = [],
error,
isLoading,
} = useSWR(
query ? `/api/products?query=${encodeURIComponent(query)}` : null,
fetcher
)
if (!query) return null
if (error) return <p>Failed to load products.</p>
if (isLoading) return <p>Loading products...</p>
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}使用 Suspense 处理客户端数据#
当希望由最近的 Suspense 边界定义加载 UI 时,使用 suspense: true。将交互式外壳保持在边界之外,以便结果加载期间它仍然可用:
'use client'
import { Suspense } from 'react'
import useSWR from 'swr'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product[]> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch products')
return response.json()
}
export function ProductAutocomplete({ query }: { query: string }) {
if (!query) return null
return (
<Suspense fallback={<p>Loading products...</p>}>
<ProductResults query={query} />
</Suspense>
)
}
function ProductResults({ query }: { query: string }) {
const { data } = useSWR(
`/api/products?query=${encodeURIComponent(query)}`,
fetcher,
{ suspense: true }
)
return (
<ul>
{data.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
)
}使用无条件 key 时,SWR 会在 Suspense 完成后定义 data。使用最近的错误边界处理请求错误。
当请求正在运行且没有已加载的数据可显示时,isLoading 值为 true。只要请求正在运行(包括后台重新验证),isValidating 值就为 true。
在 SWR key 中使用稳定的请求输入。在渲染期间创建的值(例如 Date.now() 或 new Date())会在重新挂载后生成新的缓存条目。对于滚动时间范围,请按预期的刷新间隔更新 key。
使用 suspense: true 时,Suspense 会处理初始的无数据状态。同一 key 的后续重新验证会保持当前数据的渲染,而不会再次显示 Suspense 回退内容。使用 isValidating 提供后台刷新反馈。了解更多关于 SWR 加载状态的信息。
了解更多:SWR 数据获取。
小知识: 当独立的 Suspense 读取在兄弟组件中渲染时,它们可以并行启动。同一组件中的多个 Suspense 读取会按顺序执行。了解更多关于网络瀑布流和 SWR Suspense的信息。
从 Server Component 提供初始数据#
当初始渲染需要数据且 SWR 应继续在浏览器中管理该数据时,使用服务端提供数据模式。借助 SWR 2.3.0 和 React 19,Server Component 可以在客户端接管之前提供回退数据。
将 <SWRConfig> 的作用范围限定在拥有该数据的路由段。该 provider 将 fallback 保持在其使用者附近,避免将功能数据添加到共享布局中:
import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // 某个服务端函数
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }: PageProps<'/products/[id]'>) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }: { id: string }) {
return (
<SWRConfig
value={{
fallback: {
// 未等待:只有读取此 key 的组件会挂起
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}import { Suspense } from 'react'
import { SWRConfig } from 'swr'
import { getProduct } from './data' // 某个服务端函数
import { productCache } from './product-cache'
import { ProductView } from './product-view'
export default function Page({ params }) {
return (
<Suspense fallback={<p>Loading…</p>}>
{params.then(({ id }) => (
<ProductData id={id} />
))}
</Suspense>
)
}
function ProductData({ id }) {
return (
<SWRConfig
value={{
fallback: {
// 未等待:只有读取此 key 的组件会挂起
[productCache.key(id)]: getProduct(id),
},
}}
>
<ProductView id={id} />
</SWRConfig>
)
}fallback 和 Client Component 必须使用相同的 SWR key。只定义一次 key,使两个调用点共享同一标识:
export const productCache = {
key: (id: string) => `/api/products/${id}`,
}export const productCache = {
key: (id) => `/api/products/${id}`,
}在该页面示例中,params.then() 返回的 Promise 会使 fallback 保持可见,直到路由参数解析完成。然后 ProductData 为 SWR fallback 创建一个单独的、未等待的 getProduct(id) Promise。React 通过 React Server Component payload 传递该 Promise,读取匹配 key 的组件会挂起,直到数据解析完成。
Client Component 使用相同的 key 通过 useSWR 读取数据:
'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
type Product = { id: string; name: string }
async function fetcher(url: string): Promise<Product> {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }: { id: string }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}'use client'
import useSWR from 'swr'
import { productCache } from './product-cache'
async function fetcher(url) {
const response = await fetch(url)
if (!response.ok) throw new Error('Failed to fetch product')
return response.json()
}
export function ProductView({ id }) {
const { data } = useSWR(productCache.key(id), fetcher, { suspense: true })
return <h1>{data.name}</h1>
}小知识:
fallback的 key 与useSWR的 key 必须完全一致。如果两者不一致,SWR 会忽略 fallback 值并在客户端获取数据。
fallback 提供该 hook 的初始值。默认情况下,SWR 将 fallback 数据视为已过期,并在 hydration 后启动浏览器重新验证。
SWR 不为 fallback 数据提供基于时间的新鲜度窗口。设置 revalidateIfStale: false 会在 hook 挂载时若已有缓存数据则跳过重新验证。与 TanStack Query 的 staleTime 不同,此设置适用于每次挂载。
聚焦、重新连接、轮询和 mutate 仍可重新验证该 key。若要定时刷新,请设置 refreshInterval。
SWR key 指向一个使用 GET 方法的 Route Handler。该 Route Handler 可以调用提供 fallback 的同一个 getProduct 函数,而浏览器则使用该 URL 进行重新验证和轮询。
了解更多:SWR 参数与 key和SWR 与 Next.js App Router 结合使用。
使用 Cache Components 缓存服务端提供的数据#
在使用此模式之前,先在 next.config.ts 中启用 cacheComponents。然后你可以缓存用作 SWR fallback 的服务端数据。添加 use cache、选择一个 cacheLife 配置文件,并应用 cacheTag,以便变更操作可以使其失效:
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id: string) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(id) {
'use cache'
cacheLife('max')
cacheTag(`product:${id}`)
const product = await db.product.findUnique({ where: { id } })
if (!product) throw new Error('Product not found')
return product
}此示例使用 cacheLife('max'),因为写入操作会使产品标签失效。在该缓存配置中,stale 控制 Next.js 客户端缓存可复用预取 payload 的时长,而 revalidate 和 expire 控制服务端缓存。当服务端值需要随时间刷新时,请选择更短的配置。
SWR 拥有独立的浏览器缓存,因此其重新验证选项无需与 cacheLife 匹配。
当同一变更操作既更新浏览器缓存又使缓存的服务端数据失效时,你可以在一个共享契约中定义这两种标识:
export const productCache = {
key: (id: string) => `/api/products/${id}`,
+ tag: (id: string) => `product:${id}`,
} export const productCache = {
key: (id) => `/api/products/${id}`,
+ tag: (id) => `product:${id}`,
}然后服务端函数可以调用 cacheTag(productCache.tag(id))。请让该契约不依赖仅限服务端或仅限客户端的导入,以便两个缓存层都能复用它。
在变更操作后协调服务端和客户端缓存#
fallback 提供初始值。hydration 之后,SWR 管理浏览器缓存和重新验证。对于复用数据,请将 SWR key 和服务端标签放在同一个缓存契约中:
export const activityCache = {
key: '/api/activity/unread',
tag: (userId: string) => `activity:${userId}`,
}export const activityCache = {
key: '/api/activity/unread',
tag: (userId) => `activity:${userId}`,
}对 fallback、Client Component 读取和变更操作使用相同的 key。使用 SWR 时,将写入操作传给 mutate 并提供 optimisticData。SWR 会立即显示乐观值,并在写入失败时回滚。此示例在 action 成功后保留乐观值,因为最终值是已知的:
'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}'use client'
import { useSWRConfig } from 'swr'
import { markActivityReadAction } from './actions'
import { activityCache } from './activity-cache'
export function MarkReadButton() {
const { mutate } = useSWRConfig()
function markRead() {
return mutate(
activityCache.key,
async () => {
await markActivityReadAction()
return { count: 0 }
},
{
optimisticData: { count: 0 },
revalidate: false,
rollbackOnError: true,
throwOnError: false,
}
)
}
return <button onClick={markRead}>Mark read</button>
}Server Action 写入数据库,并使用 updateTag 使带标签的服务端数据过期。使用 cacheTag 为缓存的服务端查询添加标签,使标签匹配:
'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}'use server'
import { updateTag } from 'next/cache'
import {
getCurrentUserId,
markActivityRead as markActivityReadInDatabase,
} from './data'
import { activityCache } from './activity-cache'
export async function markActivityReadAction() {
const userId = await getCurrentUserId()
await markActivityReadInDatabase(userId)
updateTag(activityCache.tag(userId))
}乐观的 SWR 值会更新当前屏幕。updateTag 确保下一次缓存的服务端读取返回最新的活动数据。
小知识: 当 Server Action 更改了必须立即反映写入结果的缓存读取时,调用
updateTag。未缓存的读取没有可更新的服务端标签。有关其他失效行为,请参阅客户端数据获取。
请参阅在线 next-spa-patterns 演示及其源代码。了解更多关于 SWR 变更与乐观更新以及 SWR 文档的内容。