Skip to content

How to use SWR

A short SWR tutorial

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

You install it with

npm install swr

and you have to define a fetcher function, I always use the same in a lib/fetcher.js file:

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

You import it at the top of your component's file:

import fetcher from 'lib/fetcher'

Then you can start using it.

At the top of a component, import useSWR:

import useSWR from 'swr'

Then inside the component, at the top, we call useSWR to load the data we need:

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

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

You can pass an additional object to useSWR with some options, for example I use this to limit the number of revalidation SWR does, so I don't get repeated connections to the endpoint when I'm in development mode:

const { data } = useSWR(`/api/data`, fetcher, {
  revalidateOnFocus: false,
  revalidateOnReconnect: false,
  refreshWhenOffline: false,
  refreshWhenHidden: false,
  refreshInterval: 0
→ Download my free JavaScript Handbook!



You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about js: