SWR (Stale While Revalidate) is a React hook library by Vercel that simplifies data fetching and caching in Next.js. It uses the stale-while-revalidate strategy, meaning cached data is shown instantly for fast rendering, while fresh data is fetched in the background to update the UI. This ensures both speed and up-to-date content for a smoother user experience.
- Returns the data from cache (stale)
- Sends the fetch request (revalidate), and then
- Comes with the up-to-date data again.
Steps to Create Next.js Project
Steps taken to set up your next.js project, given that one has node & npm installed on their device.
Step 1: Check the node & npm versions by running below command
node -v && npm -vStep 2: Create a directory, and after reaching the targeted directory in terminal perform
npm install --save next react react-domStep 3: Create a file in index.js in the pages folder (basically pages/index.js), add the following code, and run npm start to see it in action!
// Filename - pages/index.js
import React from "react";
import Link from "next/link";
export default class extends React.Component {
render() {
return (
<div>
<h1>Hello Geeks</h1>
</div>
);
}
}
Implementing SWR to fetch data from API
We'll perform a data-fetch using SWR & isomorphic-unfetch with the powerful Next.js, the two dependencies that need to be installed (commands given in the code).
// Filename - /pages/index.js
/* Install by using the CLI - npm i swr */
import useSWR from "swr";
import fetch from "../libs/fetch";
function StateNameAN() {
const { data, error } = useSWR(
"https://gist.githubusercontent.com/shubhamjain/35ed77154f577295707a/raw/7bc2a915cff003fb1f8ff49c6890576eee4f2f10/IndianStates.json",
fetch
);
/* In case API fails */
if (error) return <div>failed to load</div>;
/* While result API loads */
if (!data) return <div>loading...</div>;
/* After response from the API is received */
return <div>Hello {data.AN}!</div>;
}
export default function IndexPage() {
return (
<div>
<StateNameAN />
</div>
);
}
// Filename - /libs/fetch.js
/* Install by using the CLI - npm i isomorphic-unfetch */
import fetch from "isomorphic-unfetch";
export default async function (...args) {
const res = await fetch(...args);
return res.json();
}
Output:
Hello Andaman and Nicobar Islands!Advantages of SWR
Apart from Custom API calls & REST API integration, what comes with Zeit's SWR are described below.
- Focus Revalidation: When you re-focus a page or switch between tabs in the browser, SWR automatically revalidates data.
- Fast Navigation: SWR automatically revalidates the data from the origin as soon as data is rendered from the cache.
- Refetch on Interval: SWR will give you the option to automatically fetch data, where prefetching will only take place of the component associated with the hook is on the screen.
- Local Mutation: Applying changes to data locally, i.e. always updated to the most recent data.
- Dependent Fetching: SWR allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data, fetch to happen.
- Scalable: SWR scales extremely well because it requires very little effort to write applications that automatically and eventually converge to the most recent remote data.
Disadvantages of SWR
- A major disadvantage of using SWR is that it might lead the user looking at stale data, which can happen because of a lack of proper implementation of the API, error in updating the displayed information, and possibly many others.
- Apart from creating a bad user experience, this can also be the sole reason for the setback of a company! Imagine a well-established company in finance, can they afford to have their users looking at the stale data!? Nope, and that is why an accurate implementation and use of SWR is required.