AI Workshop: learn to build apps with AI →
Other JavaScript Libraries: SWR

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


SWR

SWR is a React Hooks library for data fetching, created by Vercel. The name “SWR” comes from stale-while-revalidate, a cache revalidation strategy.

In a Next.js app, SWR is one of the best ways to do a GET request.

Installation

npm install swr

Setting up the fetcher

You need to define a fetcher function. Create a lib/fetcher.js file:

const fetcher = (...args) => fetch(...args).then((res) => res.json())
export default fetcher

Import it at the top of your component’s file:

import fetcher from 'lib/fetcher'

Basic usage

At the top of a component, import useSWR:

import useSWR from 'swr'

Then inside the component, call useSWR to load the data you need:

const { data } = useSWR(`/api/data`, fetcher)

In addition to the data property, the object returned by useSWR contains isLoading and isError. isLoading is especially useful to show some kind of “loading…” visual indication.

Configuration options

You can pass an additional object to useSWR with some options. For example, to limit the number of revalidations SWR does (useful in development mode):

const { data } = useSWR(`/api/data`, fetcher, {
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
  refreshWhenOffline: false,
  refreshWhenHidden: false,
  refreshInterval: 0
})

Conditional data loading

Sometimes you want to make the request only if you have some data first.

For example, you might need to check if the user is logged in before sending a request to a /api/user endpoint:

import fetcher from 'lib/fetcher'

const { data: userData } = useSWR(
  session && session.user ? `/api/user` : null,
  fetcher
)

The first parameter is the URL. If it’s null, then SWR does not perform the request.

This pattern is useful when:

  • You need to wait for authentication state
  • One request depends on data from another request
  • You want to conditionally fetch based on user input

Lessons in this unit:

0: Introduction
1: jQuery
2: Axios
3: Moment.js
4: ▶︎ SWR
5: XState
6: PeerJS