DEV Community

Odukwe Precious Chiemeka
Odukwe Precious Chiemeka

Posted on

How To Handle Data Fetching in Next.js Using SWR

Handling data fetching in Next.js can be tricky, but using the SWR aka (stale-while-revalidate) library makes it much more manageable. SWR is a lightweight library that allows you to handle data fetching and caching in your Next.js application efficiently.

SWR offers many critical features, such as its ability to revalidate data automatically, caching, etc. This article provides information on how to set up and integrate the SWR library in your Next.js project.

Installing SWR

To use the SWR library in your Next.js application, you will first need to install the library by running the following command in your terminal:

npm install swr
Enter fullscreen mode Exit fullscreen mode

If you are using yarn, run this command:

yarn add swr
Enter fullscreen mode Exit fullscreen mode

Next, you import the useSWR hook to easily fetch data from your API. The useSWR hook is a hook for handling data fetching and caching. The useSWR hook takes a key (URL or identifier) as an input and returns an object that contains the data fetched, error, and loading state.

To use the useSWR hook, you must create a fetcher function containing the fetch request.

For example:

const fetcher = async (url) => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}
Enter fullscreen mode Exit fullscreen mode

After creating the fetcher function, you use it in the useSWR hook:

import useSWR from 'swr'

const fetcher = async (url) => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

export default function Home() {
  const { data, error, isLoading } = useSWR('https://api.example.com/data', fetcher)

  if (error) return <div>Failed to load</div>
    if (isLoading) return <div>Loading...</div>

    return (
        <div>{data.title}</div>
    )
}

Enter fullscreen mode Exit fullscreen mode

In the code block above, the useSWR hook returns an object with two properties: data, error, and isLoading. If there is an error fetching the data, it returns the message "Failed to load.” If the data is not yet loaded, it returns the message "Loading...".

You can also pass a configuration object as the second argument to the useSWR hook. This object allows you to customize how SWR handles data fetching and caching.

Handling Automatic Revalidation

One of the essential features of the SWR library is its ability to revalidate stale data automatically. The revalidateOnFocus, refreshInterval, and revalidatOnReconnect properties are responsible for this ability. The revalidateOnFocus ensures that when a user re-focus on your web page or switches between tabs, the SWR library will make another fetch request to the API.

By default, the revalidateOnFocus feature is enabled. To turn it off, you set the revalidateOnFocus property to false.

Like so:

const { data, error, isLoading } = useSWR('https://api.example.com/data', fetcher, 
{ revalidateOnFocus: false }
)
Enter fullscreen mode Exit fullscreen mode

The revalidateOnReconnect option ensures that SWR revalidates the data whenever a user regains connection to the internet after having previously lost it. This is very useful in certain situations, but in cases where it is unnecessary, you can disable it.

To disable it, you set the revalidateOnReconnect property to false:

const { data, error, isLoading } = useSWR('https://api.example.com/data', fetcher, 
    { revalidateOnReconnect: false }
)
Enter fullscreen mode Exit fullscreen mode

You can determine how often the data is fetched from the API using the refreshInterval property. The refreshInterval property is a time interval in milliseconds that determines how often your data is fetched from an API. The default value is 0.

Setting the refreshInterval to a positive value ensures that the data will be re-fetched at the specified interval.

Like so:

const { data, error, isLoading } = useSWR('https://api.example.com/data', fetcher, 
    { refreshInterval: 5000 }
)
Enter fullscreen mode Exit fullscreen mode

In cases where the data you are fetching from the API remains static, revalidating it won't produce any changes. In such cases, the automatic revalidation feature of the SWR library is unnecessary; it will be better to disable it. To disable the automatic revalidation feature, you set the revalidateOnFocus and revalidateOnReconnect properties to false and leave the refreshInterval at 0.

Another method of disabling automatic revalidation is to use the useSWRImmutable hook in place of the regular useSWR hook to fetch data. The useSWRImutable hook is identical to the useSWR hook but offers an efficient way to handle immutable data. It uses the useSWR hook internally to fetch and revalidate data and ensures that the data remains unchanged between renders.

For example:

import useSWRImmutable from 'swr/immutable'

const { data, error, isLoading } = useSWRImmutable('https://api.example.com/data', fetcher)
Enter fullscreen mode Exit fullscreen mode

Conclusion

SWR is an excellent library for data fetching and caching in your Next.js application. It's easy to use, customizable, and offers features like stale-while-revalidate and automatic revalidation, making it an excellent choice for any Next.js application that needs to fetch data from an API. This article will help you integrate the SWR into your next Next.js project.

Top comments (0)