SWR

“SWR” 这个名字来自于 stale-while-revalidate:一种由 HTTP RFC 5861 (opens in a new tab) 推广的 HTTP 缓存失效策略。这种策略首先从缓存中返回数据(过期的),同时发送 fetch 请求(重新验证),最后得到最新数据。

使用 SWR,组件将会不断地自动获得最新数据流。
UI 也会一直保持快速响应

概览

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('/api/user', fetcher)
 
  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

该示例中,useSWR hook 接受一个字符串 key 和一个函数 fetcherkey 是数据的唯一标识符(通常是 API URL),并传递给 fetcherfetcher 可以是任何返回数据的异步函数,你可以使用原生的 fetch 或 Axios 之类的工具。

基于请求的状态,这个 hook 返回 2 个值:dataerror

特性

仅需一行代码,你就可以简化项目中数据请求的逻辑,并立即拥有以下这些不可思议的特性:

  • 极速轻量可重用的 数据请求
  • 内置 缓存 和重复请求去除
  • 实时 体验
  • 传输和协议不可知
  • 支持 SSR / ISR / SSG
  • 支持 TypeScript
  • React Native

SWR 涵盖了性能,正确性和稳定性的各个方面,以帮你建立更好的体验:

  • 快速页面导航
  • 间隔轮询
  • 数据依赖
  • 聚焦时重新验证
  • 网络恢复时重新验证
  • 本地缓存更新 (Optimistic UI)
  • 智能错误重试
  • 分页和滚动位置恢复
  • React Suspense

以及 更多

社区

starsdownloadslicense

SWR 由 Next.js (opens in a new tab)(React 框架)背后的同一团队创建。 在 Twitter 上关注 @vercel (opens in a new tab) 未来项目更新

欢迎加入 GitHub 上的讨论 (opens in a new tab)

Design Assets

Feel free to use the Nextra logo and other assets in your project. But please don't modify the logo, and don't use the logo to represent your project or product.

NameDescriptionPreview
IconUseful for favicons, app icons, link icons, etc.Nextra icon
LogoFull Nextra logoNextra logo
Social CardThe Nextra social cardNextra card

License

The Nextra project and themes are licensed under the MIT license.