What is swr?
The swr npm package 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 HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.
What are swr's main functionalities?
Data Fetching
SWR provides a hook called useSWR for data fetching. You can pass a key and a fetcher function, and it will return the data, error, and other useful values for handling the UI state.
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return <div>Hello, {data.name}!</div>
}
Automatic Revalidation
SWR automatically revalidates data when a user focuses on the window or when the network is reconnected. It can also be configured to revalidate data at a fixed interval.
import useSWR from 'swr'
function Profile() {
const { data } = useSWR('/api/user', fetcher, {
refreshInterval: 3000
})
// data will be revalidated every 3 seconds
return <div>{data.name}</div>
}
Local Mutation
SWR allows you to mutate the local data immediately and revalidate it in the background. This provides an optimistic UI update experience.
import useSWR, { mutate } from 'swr'
function updateUsername(name) {
mutate('/api/user', { ...data, name }, false)
fetch('/api/user', {
method: 'POST',
body: JSON.stringify({ name })
}).then(() => {
mutate('/api/user')
})
}
Other packages similar to swr
react-query
React Query is another library for fetching, caching, and updating data in React applications. It provides more advanced features like query cancellation, background fetching, and even pagination helpers. React Query is often compared to SWR for its similar use cases but offers a different API and additional features.
apollo-client
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It is more complex and powerful than SWR, designed specifically for GraphQL, and provides features like caching, optimistic UI, and subscription support.
axios
Axios is a promise-based HTTP client for the browser and Node.js. While it is not a hook-based data fetching library like SWR, it is often used for making HTTP requests in React applications. Developers would use Axios for fetching data and then manage the caching and state themselves or with additional libraries.
Introduction
SWR is a React Hooks library for data fetching.
The name “SWR” is derived from stale-while-revalidate
, a cache invalidation strategy popularized by HTTP 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 and reusable data fetching
- Transport and protocol agnostic
- Built-in cache 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 get a stream of data updates constantly and automatically. Thus, the UI will be always fast and reactive.
View full documentation and examples on swr.vercel.app.
Quick Start
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>
}
In this example, the React Hook useSWR
accepts a key
and a fetcher
function.
The key
is a unique identifier of the request, normally the URL of the API. And the fetcher
accepts
key
as its parameter and returns the data asynchronously.
useSWR
also returns 3 values: data
, isLoading
and error
. When the request (fetcher) is not yet finished,
data
will be undefined
and isLoading
will be true
. When we get a response, it sets data
and error
based on the result
of fetcher
, isLoading
to false and rerenders the component.
Note that fetcher
can be any asynchronous function, you can use your favourite data-fetching
library to handle that part.
View full documentation and examples on swr.vercel.app.
Authors
This library is created by the team behind Next.js, with contributions from our community:
Contributors
Thanks to Ryan Chen for providing the awesome swr
npm package name!
License
The MIT License.