Open In App

Next.js SWR (Stale While Revalidate) Introduction

State While Revalidate is React Hooks library for remote data fetching, created by Zeit. It is used for 

Google says about the concept of SWR: 



 “It helps developers balance between immediacy—loading cached content right away—and freshness—ensuring updates to the cached content are used in the future. If you maintain a third-party web service or library that updates on a regular schedule, or your first-party assets tend to have short lifetimes, then stale-while-revalidate may be a useful addition to your existing caching policies.”

A Cache-Control response header that contains stale-while-revalidate should also contain max-age, and the number of seconds specified via max-age is what determines staleness. Any cached response newer than max-age is considered fresh, and older cached responses are stale. Simply put, SWR automatically revalidates the data from the origin as soon as data is rendered from the cache, this will render the pages much faster and after rendering the page the data is updated with the latest one.
 



Advantages of SWR: Apart from Custom API calls & REST API integration, what comes with Zeit’s SWR are described below.

Disadvantages of SWR: 

Introduction to Next.js:

Next.js is a react based framework. It is based on react, webpack & babel. It is known for its automatic code-splitting, hot-code reloading (i.e. reloads as soon as the changes get saved) & most importantly, Server Side Rendering. This puts up this framework on top of the recommended toolchains suggested at React documentation.

Steps taken to set up your next.js project, given that one has node & npm installed on their device. 




// The code for 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> 
        
    }   

Using Next.js with SWR to fetch an 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).




// The code for /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(
  /* 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>
  );
}




// The code for /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! 

 


Article Tags :