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 -v
Step 2: Create a directory, and after reaching the targeted directory in terminal perform
npm install --save next react react-dom
Step 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!
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).
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.