NextJS: Using SWR based Data Fetching For Client Side Components

Manish Sharma
2 min readAug 4, 2023
NextJS and SWR

This article mentions data fetching strategy for Client Side Components in NextJS. For Server Side components refer to my previous article .

“I am fed up of making HTTP request again and again to same end-point to get data”

“Why don’t you cache responses for future use ?”

“But what if after some time the response becomes stale?”

“Make a fresh request, update UI with fresh response and also cache this fresh response for future use”

“But this logic has to be repeated across multiple pages. Do we have an easy to use approach for this ?”

“Yes, use SWR”

“What exactly is SWR?”

So how can I define SWR as ?

SWR is a data fetching technique that makes use of http-cache based invalidation strategy to improve user experience.

If requested data is not available in cache, it makes http request to get data, stores it in cache and returns data

If requested data is in cache and not stale, it returns cached data

If requested data is in cache but stale, it it makes http request to get data, stores it in cache and returns data.

Remeber SWR is designed to work with NextJS Client Side components in NextJS .

How SWR Works
How SWR Works

How can I implement SWR in React ?

Install

npm i swr

Use

First define a fetcher. A fetcher is an async function that accepts key of SWR and returns the data in json or text format.

const fetcher = (…args) => fetch(…args).then((res) => res.text());

Now use fetcher with SWR:

// No refresh interval
const { data, error } = useSWR("http://numbersapi.com/" + n, fetcher);

or

const { data, error } = useSWR("http://numbersapi.com/5" , fetcher, {
refreshInterval: 6000,
});

Automatic Revalidation

When ever web page using SWR gains focus, SWR revalidates data automatically, thus keeping ui ‘fresh’ with latest data.

On demand Revalidation

Use mutate object to get fresh copy of data.

const { mutate } = useSWRConfig();
mutate("http://numbersapi.com/5");

Let’s see it in action

Following API returns random fact about given number. Each invocation returns a random fact.

http://numbersapi.com/<number>

Our Component has a button which when clicked, performs on-demand revalidation using mutate().

Using SWR On demand Revalidation with NextJS
Using SWR On demand Revalidation with NextJS

The code is:

You may download source code from this repo.
Happy Coding.

--

--