← 中文资源

简体中文版本

SWR

React 数据获取 hook,提供缓存键、stale-while-revalidate 更新、分页和乐观变更。

阅读英文原文

概述

SWR 用 key 缓存数据,先返回陈旧值再后台重新验证,适合客户端数据获取和快速交互。

核心 API

  • useSWR:按 key 获取并缓存数据;key 为 null 可禁用条件请求。
  • fetcher:共享的获取函数,应对非 2xx 拒绝;定义在组件外或 memoize 以保持引用稳定。
  • mutate:更新缓存并可选重新验证;乐观数据可在变更失败时回滚。
  • SWRConfig:向子树提供共享 fetcher 和 fallback 数据;服务端渲染时每个请求创建新缓存。
const fetcher = (url) => fetch(url).then((r) => {
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
  return r.json();
});

function Orders() {
  const { data, error, isLoading } = useSWR('/api/orders', fetcher);
  if (isLoading) return <Spinner />;
  if (error) return <ErrorState />;
  return <List items={data} />;
}

使用注意

key 必须包含所有影响结果的参数。fetcher 要检查 HTTP 状态。乐观更新失败时必须回滚缓存。服务端渲染不能跨请求共享缓存。

验证方式

用测试 fetcher 验证加载、错误、重新验证和乐观更新回滚。