swr
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSWR — React Hooks for Data Fetching
SWR — 用于数据获取的React Hooks
You are an expert in SWR v2, the React Hooks library for data fetching by Vercel. SWR implements the stale-while-revalidate HTTP cache invalidation strategy — serve from cache first, then revalidate in the background.
您是Vercel推出的SWR v2(一款用于数据获取的React Hooks库)专家。SWR 实现了stale-while-revalidate HTTP缓存失效策略——优先从缓存返回数据,然后在后台重新验证。
Installation
安装
bash
npm install swrbash
npm install swrCore API
核心API
useSWR
useSWRuseSWR
useSWRtsx
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then(res => res.json())
function Profile() {
const { data, error, isLoading, mutate } = useSWR('/api/user', fetcher)
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error loading data</div>
return <div>Hello, {data.name}</div>
}Key parameters:
- — unique string, array, or function identifying the resource (often a URL)
key - — async function that receives the key and returns data
fetcher - — optional config object
options
Return values: , , , ,
dataerrorisLoadingisValidatingmutatetsx
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then(res => res.json())
function Profile() {
const { data, error, isLoading, mutate } = useSWR('/api/user', fetcher)
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error loading data</div>
return <div>Hello, {data.name}</div>
}关键参数:
- — 标识资源的唯一字符串、数组或函数(通常是URL)
key - — 接收key并返回数据的异步函数
fetcher - — 可选的配置对象
options
返回值: , , , ,
dataerrorisLoadingisValidatingmutateuseSWRMutation
— Remote Mutations
useSWRMutationuseSWRMutation
— 远程变更
useSWRMutationtsx
import useSWRMutation from 'swr/mutation'
async function updateUser(url: string, { arg }: { arg: { name: string } }) {
return fetch(url, { method: 'POST', body: JSON.stringify(arg) }).then(res => res.json())
}
function Profile() {
const { trigger, isMutating } = useSWRMutation('/api/user', updateUser)
return (
<button disabled={isMutating} onClick={() => trigger({ name: 'New Name' })}>
Update
</button>
)
}tsx
import useSWRMutation from 'swr/mutation'
async function updateUser(url: string, { arg }: { arg: { name: string } }) {
return fetch(url, { method: 'POST', body: JSON.stringify(arg) }).then(res => res.json())
}
function Profile() {
const { trigger, isMutating } = useSWRMutation('/api/user', updateUser)
return (
<button disabled={isMutating} onClick={() => trigger({ name: 'New Name' })}>
Update
</button>
)
}useSWRInfinite
— Pagination & Infinite Loading
useSWRInfiniteuseSWRInfinite
— 分页与无限加载
useSWRInfinitetsx
import useSWRInfinite from 'swr/infinite'
const getKey = (pageIndex: number, previousPageData: any[]) => {
if (previousPageData && !previousPageData.length) return null
return `/api/items?page=${pageIndex}`
}
function Items() {
const { data, size, setSize, isLoading } = useSWRInfinite(getKey, fetcher)
const items = data ? data.flat() : []
return (
<>
{items.map(item => <div key={item.id}>{item.name}</div>)}
<button onClick={() => setSize(size + 1)}>Load More</button>
</>
)
}tsx
import useSWRInfinite from 'swr/infinite'
const getKey = (pageIndex: number, previousPageData: any[]) => {
if (previousPageData && !previousPageData.length) return null
return `/api/items?page=${pageIndex}`
}
function Items() {
const { data, size, setSize, isLoading } = useSWRInfinite(getKey, fetcher)
const items = data ? data.flat() : []
return (
<>
{items.map(item => <div key={item.id}>{item.name}</div>)}
<button onClick={() => setSize(size + 1)}>Load More</button>
</>
)
}Global Configuration
全局配置
Wrap your app (or a subtree) with to set defaults:
SWRConfigtsx
import { SWRConfig } from 'swr'
function App() {
return (
<SWRConfig value={{
fetcher: (url: string) => fetch(url).then(res => res.json()),
revalidateOnFocus: false,
dedupingInterval: 5000,
}}>
<Dashboard />
</SWRConfig>
)
}使用包裹您的应用(或子树)来设置默认值:
SWRConfigtsx
import { SWRConfig } from 'swr'
function App() {
return (
<SWRConfig value={{
fetcher: (url: string) => fetch(url).then(res => res.json()),
revalidateOnFocus: false,
dedupingInterval: 5000,
}}>
<Dashboard />
</SWRConfig>
)
}Revalidation Strategies
重新验证策略
| Strategy | Option | Default |
|---|---|---|
| On window focus | | |
| On network recovery | | |
| On mount if stale | | |
| Polling | | |
| Manual | Call | — |
| 策略 | 选项 | 默认值 |
|---|---|---|
| 窗口聚焦时 | | |
| 网络恢复时 | | |
| 挂载时若数据过期 | | |
| 轮询 | | |
| 手动 | 调用 | — |
Optimistic Updates
乐观更新
tsx
const { trigger } = useSWRMutation('/api/user', updateUser, {
optimisticData: (current) => ({ ...current, name: 'New Name' }),
rollbackOnError: true,
populateCache: true,
revalidate: false,
})tsx
const { trigger } = useSWRMutation('/api/user', updateUser, {
optimisticData: (current) => ({ ...current, name: 'New Name' }),
rollbackOnError: true,
populateCache: true,
revalidate: false,
})Conditional Fetching
条件式获取
Pass or a falsy key to skip fetching:
nulltsx
const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher)传入或假值key来跳过数据获取:
nulltsx
const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher)Error Retry
错误重试
SWR retries on error by default with exponential backoff. Customize with:
tsx
useSWR(key, fetcher, {
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (error.status === 404) return // Don't retry on 404
if (retryCount >= 3) return // Max 3 retries
setTimeout(() => revalidate({ retryCount }), 5000)
},
})SWR默认在出错时使用指数退避策略进行重试。可通过以下方式自定义:
tsx
useSWR(key, fetcher, {
onErrorRetry: (error, key, config, revalidate, { retryCount }) => {
if (error.status === 404) return // 404错误不重试
if (retryCount >= 3) return // 最多重试3次
setTimeout(() => revalidate({ retryCount }), 5000)
},
})Key Rules
关键规则
- Keys must be unique — two calls with the same key share cache and deduplicate requests
useSWR - Fetcher is optional when set via
SWRConfig - globally revalidates any hook matching that key
mutate(key) - Array keys like — the fetcher receives the full array
useSWR(['/api/user', id], fetcher) - Never call hooks conditionally — use conditional keys () instead
null
- Key必须唯一 — 两个使用相同key的调用共享缓存并去重请求
useSWR - 当通过设置后,Fetcher是可选的
SWRConfig - 全局重新验证所有匹配该key的钩子
mutate(key) - 数组key 如— fetcher会接收完整数组
useSWR(['/api/user', id], fetcher) - 切勿条件式调用钩子 — 改用条件式key()替代
null