DEV Community

loading...

Use SWR for a better data fetching

miangame profile image Miguel A. Gavilán Merino ・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 (2)

pic
Editor guide
Collapse
jwp profile image
John Peters

This is cool thanks!

Collapse
ecyrbe profile image
ecyrbe

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