What is: SWR – React Hooks remote data fetching

What is it use for?

It allows for fetching, caching or refetching data in realtime data using React Hooks. SWR, short for state-while-revalidate, is created exactly as the name implies.

📣

SWR’s goal is to serve initially the data from cache -yes, so that you can consume it right away even though it might already be stale-, while surreptitiously, a fetch request (revalidation) is being sent in the background, and once it is ready, the data will be serve to you automatically.

Why should you care?

Well, you would if need a fast and reactive UI that is being constantly and automatically updated with a stream of data.

Why choose SWR over Axios or Fetch?

Essentially, SWR is useful when you need to request data under the hood (using Fetch API) from the server.

Some notable SWR features:

  1. Paginate your data using useSWRpages
  2. Fetch data that depends on another request
  3. Recover a scroll position from a given page

How to start?

yarn add swr
Or with npm:
npm install swr

The only thing we have to do is give the useSWR hook the needed parameters to make the request.

Now, let’s create a simple create-react-app and name it react-swr-demo, or you can name it whatever you like.

Fetching Remote Data: Local or Global?

Local – setup of SWR must be done every new file creation

Global – a fetcher function is declared once and use everywhere

First, lets use useSWR() and pass into this hook a key and a fetch function.

I am also using a simple free jsonplaceholder to build our app (https://jsonplaceholder.typicode.com/photos)

import React from "react";
import useSWR, { SWRConfig } from "swr";
import "./App.css";

const fetcher = (...args: any) => fetch(args).then((res) => res.json());
const url = "https://official-joke-api.appspot.com/jokes/programming/ten";

function App() {
  const { data, error } = useSWR(url, fetcher);

  console.log(data, error);

  return (

Take note in the useSWR that we are passing 2 arguments, the second one is fetcher.

And for that we need to create a function called fetcher, which is just a wrapper of the native fetch.

const fetcher = (...args) => fetch(...args).then(res => res.json())

This is for the normal Restful APIs with JSON data. For GraphQL API or Axios, here is an example on how to do it.

//Axios 

const fetcher = url => axios.get(url).then(res => res.data)
//GraphQL

const fetcher = query => request('https://api.graph.cool/simple/v1/movies', query)

📣 TIP: put a JSON stringify in your return statement to display the data in your UI.

return (
    <div className="App">
      <header className="App-header">
        <p>This is React SWR</p>
        <pre>{JSON.stringify(data, null, 2)} </pre>
      </header>
    </div>
  );

Now, if you check the DevTools you will notice that the data are being rendered twice. The first render is the cache data and the second is the revalidation of the data, which is really the goal strategy of useSWR.

Let’s just add an if statement for the error message.

function App() {
  const { data, error } = useSWR(url, fetcher);

  if (error) {
    return <div> There's an error</div>;
  }
  if (!data) {
    return <div>Loading data </div>;
  }

Make sure to run your app and check the data has been rendered in your browser.

For demo purposes here, I have created this the main file. This setup is a local one.

To configure SWR globally, which is a wrapper component that allows child components to use the global configuration, and that means the fetcher function.

To do this, we need to update our index.tsx or index.js file. We can also use the SWRConfig directly in the App.tsx file.

import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { SWRConfig } from "swr";
import * as serviceWorker from "./serviceWorker";


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

ReactDOM.render(
  <React.StrictMode>
    <SWRConfig value={{ fetcher }}>
      <App />
    </SWRConfig>
  </React.StrictMode>,
  document.getElementById("root")