DEV Community

loading...
Cover image for Use SWR for a better data fetching

Use SWR for a better data fetching

Miguel A. Gavilán Merino
Frontend Engineer at Genially · I am a hard worker, charismatic and a little perfectionist. I never think that something is good enough.
Updated on ・2 min read

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
Enter fullscreen mode Exit fullscreen mode

Or with npm:

npm install swr
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
  • 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())
Enter fullscreen mode Exit fullscreen mode

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.
Alt Text

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 })
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

Finally, these are just some of the things SWR provides that can make our data fetching faster and better.

Thanks for reading me!
Thank you

Discussion (4)

Collapse
ecyrbe profile image
ecyrbe • Edited

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

Collapse
iamsonika profile image
Sonika Maheshwari

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?

Collapse
javaguirre profile image
Javier Aguirre

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!

Collapse
jwp profile image
John Peters

This is cool thanks!