Intro
SWR is a React Hooks library for remote data fetching.
The name “SWR” is derived from stale-while-revalidate
, a HTTP cache invalidation strategy popularized by RFC 5861.
SWR first returns the data from cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data again.
It features:
- Transport and protocol agnostic data fetching
- Fast page navigation
- Revalidation on focus
- Interval polling
- Local mutation
- Pagination
- TypeScript ready
- Suspense mode
- Minimal API
With SWR, components will get a stream of data updates constantly and automatically, Thus, the UI will be always fast and reactive.
Quick Start
{ const data error = if error return <div>failed to load</div> if !data return <div>loading...</div> return <div>hello dataname!</div>}
In this example, the React Hook useSWR
accepts a key
and a fetch
function.
key
is a unique identifier of the data, normally a URL of the API. And the fetch
accepts
key
as its parameter and returns the data asynchronously.
useSWR
also returns 2 values: data
and error
. When the request (fetch) is not yet finished,
data
will be null
. And when we get a response, it sets data
and error
based on the result
of fetch
and rerenders the component.
API
useSWR
const data // data for the given key (or null) error // error (or null) isValidating // is validating revalidate // function to trigger a validate manually} =
SWRConfig
{ return <SWRConfig value= refreshInterval: 1000 > /* ... */ </SWRConfig>} { const data error = // ...all the SWRs inside will use `refreshInterval: 1000` // automatically. // ...}
mutate
With mutate
, you can update your local data programmatically, while
revalidating and finally replace it.
{ const data = return <div> <h1>My name is dataname</h1> <button onClick=async { const newName = dataname // send a request to the API to update the data await // update the local data immediately and revalidate (refetch) }>Uppercase my name!</button> </div>}
trigger
You can broadcast a revalidation message to all SWR data inside any component by calling
trigger(key)
.
{ return <div> <Profile /> <button onClick= { // set the cookie as expired documentcookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;' // tell all SWRs with this key to revalidate }> Logout </button> </div>}
Suspense
You can enable the suspense
option to use useSWR
with React Suspense.
{ const data = return <div>hello dataname</div>} { return <Suspense fallback=<div>loading...</div>> <Profile/> </Suspense>}
Authors
- Shu Ding (@shuding_) – ZEIT
- Guillermo Rauch (@rauchg) – ZEIT
- Joe Haddad (@timer150) - ZEIT
- Paco Coursey (@pacocoursey) - ZEIT
License
The MIT License.