- Notifications
You must be signed in to change notification settings - Fork1.3k
React Hooks for Data Fetching
License
vercel/swr
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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.
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.
This library is created by the team behindNext.js, with contributions from our community:
- Shu Ding (@shuding_) -Vercel
- Jiachi Liu (@huozhi) -Vercel
- Guillermo Rauch (@rauchg) -Vercel
- Joe Haddad (@timer150) -Vercel
- Paco Coursey (@pacocoursey) -Vercel
Thanks to Ryan Chen for providing the awesomeswr
npm package name!
The MIT License.
About
React Hooks for Data Fetching
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.