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:

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:

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

Make sure to import the fetcher function at the top of your component’s file:

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:

import useSWR from 'swr';

Inside your component, call the useSWR hook at the top to load the necessary data:

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:

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