DEV Community

Cover image for How to Use SWR with React
Ahmed Mohamed
Ahmed Mohamed

Posted on

How to Use SWR with React

Introduction

If You are Front End Developer, of Ofcourse you Use the Axios Library at Least Once in Your Projects.
Axios is Nice and One of the Best Libs that Dealing With APIs, But If I told You that There is a Library That is Better than Axios.
So, Let's Get Started...

What is SWR?

SWR is a Shortcut for stale-while-revalidate and It’s a React Hooks library for remote data fetching.

SWR Contain Three Main Stages:
1- Steal: Return Data from Cache.
2- Revalidate Send a Fetch Request.
3- Finally comes with the up-to-date data.

Now If You Wonder, Why I should use SWR?
I am still Fine With Axios.

The Thing That You should Know that SWR is not Like Axios, You can Think That It is a Superset of Axios, So You can use Axios as a part of it.
SWR contains a Lot of Features That Axios Did not Have like:

  • Fast, lightweight and reusable data fetching
  • Built-in cache and request deduplication
  • Real-time experience
  • Transport and protocol agnostic
  • SSR / ISR / SSG support -TypeScript ready
  • React Native
  • Fast page navigation
  • Polling on interval
  • Data dependency
  • Revalidation on focus
  • Revalidation on network recovery
  • Local mutation (Optimistic UI)
  • Smart error retry
  • Pagination and scroll position recovery
  • React Suspense
  • ...etc

SWR use React Suspense Technique which prevents React Component from being Rendered Until the Response is Ready and During This Time Give You a Fallback Value.


SWR Installation?

First Create React Project by the Following Command in Your Terminal:

npx create-react-app ./swr-project && cd swr-project
Enter fullscreen mode Exit fullscreen mode

Then install SWR by Following Command:

npm i swr
Enter fullscreen mode Exit fullscreen mode

After Knowing What is React SWR and How to Install it in Your Project, Let's get an example of it.

//* Imports
import axios from "axios";
import useSWR from "swr";

//* Set Axios Base URL
const apiEndPoint = "https://jsonplaceholder.typicode.com";
axios.defaults.baseURL = apiEndPoint;

//* Fetcher Function
const fetcher = (url) => axios.get(url).then((res) => res.data);

function Users() {
  const { data: users, error } = useSWR("/users", fetcher);

  if (error) return <h1>Error!</h1>;
  if (!users) return <h1>Loading...</h1>;

  return (
    <div>
      <h1>Users</h1>
      {users.map((user) => {
        return <h2>{user.name}</h2>;
      })}
    </div>
  );
}

export default Users;
Enter fullscreen mode Exit fullscreen mode

In The Above Example, We Use useSWR React Hook to fetch users data from a JSON Placeholder Website which gives us fake APIs.
As we see useSWR() Hook takes Two arguments:

  1. URL and its API End Point (in our case Users API)
  2. Fetcher Function this is the function that SWR uses to fetch the data from different APIs. You can use any library as Fetcher Function like fetch() or Axios ..etc

And Give Us two Values:

  1. Data
  2. Error

As I told You before SWR use React Suspense Technique so we can add a fallback value to show it until the data is fetched successfully, in our example we just show Loading... Word but you can replace it with nice loading animations.
So run your project to see the following result.

Users Fetching

Notice that you should handle error and loading values before your react component main content.

Make fetch function Global

One of the SWR features is that you can make the fetch function global in your project.
SWR introduces to us a Context called SWRconfig which gets the fetcher function and shares it between all project components, let's get an example to understand.

App:

//* Imports
import React from "react";
import { SWRConfig } from "swr";
import axios from "axios";
import Users from "./Users";

//* Set Axios Base URL
axios.defaults.baseURL = "https://jsonplaceholder.typicode.com/";

function App() {
  const fetcher = (url) => axios.get(url).then((res) => res.data);

  return (
    <SWRConfig
      value={{
        fetcher,
      }}
    >
      <Users />
    </SWRConfig>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

For in App component, we import SWRconfig Contact from SWR and then we wrapped the App component in it, then we add the fetcher function.

Now we can use SWR in our components without the fetcher function in the Users Component.

Users:

//* Imports
import useSWR from "swr";

function Users() {
  const { data: users, error } = useSWR("/users");

  if (error) return <h1>Error!</h1>;
  if (!users) return <h1>Loading...</h1>;

  return (
    <div>
      <h1>Users</h1>
      {users.map((user) => {
        return <h2>{user.name}</h2>;
      })}
    </div>
  );
}

export default Users;
Enter fullscreen mode Exit fullscreen mode

Make Your Fetcher function by SWR.

Now let's make our Fetcher function to use in future projects.
Our function will get the URL and return three main values:

  1. Data
  2. IsError
  3. isLoading
//* Imports
import useSWR from "swr";
import axios from "axios";

//* Fetcher Function
const fetcher = (url) => axios.get(url).then((res) => res.data);

const useFetch = (url) => {
  const { data, error } = useSWR(url, fetcher);

  return {
    data: data,
    isLoading: !data && !error,
    isError: error,
  };
};

export default useFetch;
Enter fullscreen mode Exit fullscreen mode

Notice That our Fetcher Function uses an useSWR() hook so you should use it only in react components.


Conclusion

Finally, we just know a small introduction about SWR because it has a lot of other features like pagination and Revalidations...etc, that you should try and know it.
See You in the Next Article.

Top comments (0)