How to Use SWR: A Short Tutorial
In a Next.js app, one of the most effective ways to perform a GET request is by using SWR.
To get started, you can install SWR by running the following command:
1 | npm install swr |
After installing SWR, you need to define a fetcher function. I usually create a lib/fetcher.js
file and include the following code:
1 | const fetcher = (...args) => fetch(...args).then((res) => res.json()); |
Make sure to import the fetcher
function at the top of your component’s file:
1 | import fetcher from 'lib/fetcher'; |
Now, you can start using SWR in your component. First, import the useSWR
hook at the top of your component’s file:
1 | import useSWR from 'swr'; |
Inside your component, call the useSWR
hook at the top to load the necessary data:
1 | const { data } = useSWR(`/api/data`, fetcher); |
In addition to the data
property, the object returned from the useSWR
hook also provides the isLoading
and isError
properties. isLoading
can be particularly useful for displaying a “loading…” visual indication.
You can pass an additional options object to the useSWR
hook. For example, you can use these options to limit the number of revalidations SWR performs, which can prevent repeated connections to the endpoint during development mode:
1 | const { data } = useSWR(`/api/data`, fetcher, { |
tags: [“Next.js”, “SWR”, “GET request”, “fetcher function”, “useSWR”]