Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/swrPublic

React Hooks for Data Fetching

License

NotificationsYou must be signed in to change notification settings

vercel/swr

Repository files navigation

SWR


Introduction

SWR is a React Hooks library for data fetching.

The name “SWR” is derived fromstale-while-revalidate, a cache invalidation strategy popularized byHTTP RFC 5861.SWR first returns the data from cache (stale), then sends the request (revalidate), and finally comes with the up-to-date data again.

With just one hook, you can significantly simplify the data fetching logic in your project. And it also covered in all aspects of speed, correctness, and stability to help you build better experiences:

  • Fast,lightweight andreusable data fetching
  • Transport and protocol agnostic
  • Built-incache and request deduplication
  • Real-time experience
  • Revalidation on focus
  • Revalidation on network recovery
  • Polling
  • Pagination and scroll position recovery
  • SSR and SSG
  • Local mutation (Optimistic UI)
  • Built-in smart error retry
  • TypeScript
  • React Suspense
  • React Native

...and a lot more.

With SWR, components will geta stream of data updates constantly and automatically. Thus, the UI will be alwaysfast andreactive.


View full documentation and examples onswr.vercel.app.


Quick Start

importuseSWRfrom'swr'functionProfile(){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>}

In this example, the React HookuseSWR accepts akey and afetcher function.Thekey is a unique identifier of the request, normally the URL of the API. And thefetcher acceptskey as its parameter and returns the data asynchronously.

useSWR also returns 3 values:data,isLoading anderror. When the request (fetcher) is not yet finished,data will beundefined andisLoading will betrue. When we get a response, it setsdata anderror based on the resultoffetcher,isLoading to false and rerenders the component.

Note thatfetcher can be any asynchronous function, you can use your favourite data-fetchinglibrary to handle that part.


View full documentation and examples onswr.vercel.app.


Authors

This library is created by the team behindNext.js, with contributions from our community:

Contributors

Thanks to Ryan Chen for providing the awesomeswr npm package name!


License

The MIT License.


[8]ページ先頭

©2009-2025 Movatter.jp