Use SWR for a better data fetching
Miguel A. Gavilán Merino
Posted on February 21, 2021
Hi everyone!
In this post I'm going to talk about how we can use SWR powered by Vercel to do better and easier data fetching, as well as some of the possibilities it has.
As it says in the documentation:
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.
Therefore with SWR the components will have a data stream that is constantly and automatically updated, and the UI will always be fast and reactive.
How to use SWR?
First of all we must install it with:
yarn add swr
Or with npm:
npm install swr
We will be able to use it in the following way:
import { useSWR } from '../hooks/useSWR'
const { data: users, error: Error } = useSWR<User[]>('users', UserService.getUsers)
- The
data
variable is the users fetched. - The
error
variable tells us if there has been an error during the data fetch. -
'users'
is a key that is passed to SWR. I will explain later what it is used for. -
UserService.getUsers
is the fetcher.
An example of a fetcher could be:
const fetcher = (...args) => fetch(...args).then(res => res.json())
Auto Revalidation
The power of SWR is that the data can be auto validating in different ways.
Revalidate on focus
When you re-focus a page or switch between tabs, SWR automatically revalidates data.
Revalidate on interval
We can add a time interval to SWR so that the revalidation of data occurs every so often.
import { useSWR } from '../hooks/useSWR'
const { data: users, error: Error } = useSWR<User[]>('users', UserService.getUsers, { refreshInterval: 1000 })
Revalidate with key
Earlier I mentioned that we have to pass a key to SWR.
If this key changes, the data will be automatically revalidated.
This can be combined with the use of states to have dynamic data fetching.
import { useSWR } from '../hooks/useSWR'
const [userId, setUserId] = useState(1)
const { data: user, error: Error } = useSWR<User[]>(`user-${userId}`, () => UserService.getUser(userId))
Finally, these are just some of the things SWR provides that can make our data fetching faster and better.
Posted on February 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.