Client-Side Data Fetching in Next.js using SWR


Objectives

Learn how to use SWR to handle client-side data fetching in Next.js.

Tech Stack

Client-side Fetching

Client-side data fetching is useful when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike server-side rendering APIs, client-side data fetching can be employed at the component level, granting greater flexibility and control over data retrieval. Check out more detail information in next.js documentation here.

useEffect

When discussing client-side fetching, one of the first things that may come to mind is the utilization of useEffect in React. Let's explore a typical approach for employing useEffect in React to handle such data fetching tasks.

In the above example, we are using useEffect to fetch data from an API endpoint: JSONPlaceholder. The useEffect hook is invoked after the component mounts, and the data is stored in the state variable. The data is then rendered to the page. This approach is simple, but it does have its drawbacks. For example, the data is fetched only after the component mounts, which means that the user will experience a delay in data rendering. This delay is especially noticeable when the data is fetched from a remote server. In addition, if the data is static and does not change frequently, the data is unnecessarily fetched every time the component mounts, resulting in a waste of resources.

Let's summarize the drawbacks:

  • Data delay is noticeable when the data is fetched from a remote server or low network speed.
  • Code is tedious and not intuitive. This way of fetching data is kinda imperative — manually initiating the request, updating loading states, and handling the final result.

Fortunately, there is a solution to these problems. Let's explore how we can use SWR to address these issues.

useSWR

What is SWR?

From the official website, The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

The basic API of SWR is

const { data, error } = useSWR(key, fetcher)

The fetcher here is an async function that accepts the key of SWR, and returns the data. The returned value will be passed as data, and if it throws, it will be caught as error. Normally, the key is a unique identifier of the request, such as the URL. In addition, useSWR returns data, error, isLoading, and isValidating depending on the state of the fetcher function.

Let's take a look at how SWR returns values in some scenarios:

Fetch and Revalidate: This pattern is to fetch data and revalidate it later.

Key Change: This pattern is to fetch data and change the key and revalidate it later.

Key Change + Previous Data: This pattern is to fetch data and change the key and revalidate it later with the keepPreviousData option.

Fallback This pattern is to fetch data and revalidate it later with fallback data.

Checkout more diagrams here.

SWR Implementation

Let's take a look at how we can implement SWR in our previous code example.

In the above code example, we are using SWR to fetch data from the API endpoint agian: JSONPlaceholder. The useSWR hook is invoked and the api is much simpler than the previous example. The data is then rendered to the page.

Let's summarize the advantages of using SWR for client-side data fetching:

  • Data is automatically cached and revalidated behind the scene, which means that the user will not experience a huge delay in data rendering.
  • SWR enables a more declarative approach where you simply specify what data the component needs, making your code cleaner and more straightforward.

Use axios

You can also use axios to fetch data in SWR. Let's take a look at how we can implement SWR with axios in our previous code example.

You can simply pass the axios function as the fetcher to useSWR and you are good to go! SWR is versatile and can be used with a variety of data fetching libraries. Check out more detail information in SWR documentation here.

Conclusion

That's it! We have learned how to use SWR to handle client-side data fetching in Next.js. Isn't it simple? The API is simple and easy to use. I really enjoy using this library! I hope you enjoyed this article. If you have any questions, please feel free to leave a comment below. Thank you for reading!

Resources