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.
Top comments (6)
Swr is nice. But after testing both swr and react-query, i can say that the later is far stronger with a lot more goodies.
Nowadays, when in doubt, i'll recommend using react-query
What would you say are the advantages of using react-query over SWR? I'm curious because we're using SWR, and I would like to know if it's worth the change.
Thanks!
@ecyrbe I would like to know too
Hi,
I'm testing the swr and I want that the swr get data from the server only once, at the first page view, and then, only reload the data/cache after 15 minutes...
I noriced by the web dev console that the swr hit the server all the times when I view a page, even when the response is cached.
any thoughts?
Yeah same, I want to know that how to not hit server on every refresh/reload in useSWR.
This is cool thanks!