A Look At React Hooks: useSWR for Data Fetching in React

A Look At React Hooks: useSWR for Data Fetching in React

Let's look at SWR and useSWR, and learn how it can enable our React apps to fetch, cache and work with data more efficiently

Welcome to A Look at React Hooks, a beginner-friendly series on React Hooks. In this article, let's look at the useSWR Hook.

This Hook is used to fetch data in React. Let's first learn a little bit about its background.

Overview: Data Fetching in React

Common data fetching practices such as the Fetch API or Axios library works well in React. They can be used to send and fetch data easily.

But what about caching or data pagination? Or automatic revalidation or request deduplication? Fetch and Axios only can send or fetch data, then return its response, and that's it.

In this article, let me introduce you SWR, an amazing React Hooks library that takes data fetching in React to the next level.

What is SWR?

SWR stands for stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. It basically means that it performs data fetching in 3 steps:

  1. Returns cached data first (stale)
  2. Sends the fetch request (revalidate)
  3. Returns the up-to-date data

SWR is created by Vercel and one of its advantages is that it is a fast and lightweight package. It is a layer built on top of Fetch API and therefore provides additional features on top of just data fetching. These features include caching, pagination and auto revalidation and more.

Why use SWR?

1. Built-in Cache + Real-Time Experience

When we use Fetch or Axios for data fetching in React, we usually need to show the user some loading message or spinner while data is being fetched. Using SWR's strategy, the user sees the cached (stale) data first and requests are automatically being cached. Components will always be constantly updated with the most recent data, ensuring UI will always be fast and reactive.

2. Auto Revalidation

SWR ensures that the user sees the most up-to-date data. So even with multiple tabs or windows, the data is always fresh and in sync when the window/tab is refocused.

auto.gif

Video from: swr.vercel.app/docs/revalidation

Instead of just revalidating data on focus, SWR can also revalidate data on interval, to make sure multiple sessions will render the same components based on the data.

Finally, there's revalidation on reconnect. In the event the user disconnects from the internet, SWR will automatically revalidates data once the user is online again.

3. Pagination

One of the most useful features of SWR is that it supports pagination and infinite loading of data.

page.gif

Instead of having to write your own logic with Fetch or Axios to paginate data or create an infinite loading UI for your app, SWR provides a simple Hook called useSWRInfinite to handle this for you.

4. More Features + Benefits of SWR

There are many more reasons why you should use SWR in your React apps. Some of them are:

  • Local mutation
  • Dependent fetching
  • Smart error retry
  • Supports fetching from both REST and GraphQL APIs
  • Typescript and React Native ready

Feel free to browse the official documentation for more details

Example Usage of SWR in React

Now that we learned about SWR, let's use it in a React app.

Step 1: Install package

In our React app, install the package by running:

npm install swr

Step 2: Import useSWR

SWR comes as a Hook called useSWR. Let's import it in a React component like so:

import useSWR from 'swr'

The useSWR Hook returns 2 values: data and error. It accepts a key as its first parameter, usually the URL or graphQL query of the request. The second parameter is a fetcher function.

An example of usage of the Hook is as follows:

const { data, error } = useSWR('/api/123', fetcher)

Step 3: Write a fetcher function

The fetcher function can be an asynchronous function, and you can use any data-fetching library to write the function.

For example, this is a fetcher function using Axios:

import axios from 'axios'

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

More information can be found in SWR documentation.

For this example walkthrough, we will write our fetcher function using the basic Fetch API. In a React component, we can create the function like so:

import useSWR from 'swr'

function App () {
  const fetcher = (...args) => fetch(...args).then(res => res.json())
  //...
}

Step 4: Fetch Data

Now we are ready to fetch some data. In this example, I'll use the JSONPlaceholder API to fetch some mock data.

While the data is undefined (being fetched), we can show a Loading message and if an error is returned, we can show the appropriate UI.

import useSWR from 'swr'

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

   // Add these lines
  const { data, error } = useSWR('https://jsonplaceholder.typicode.com/todos/1', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  // render data below
}

Step 5: Display Data

Finally, the component can return the data once it is fetched. The mock data in this example is in the following format:

{
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
}

Our final component will look like:

import useSWR from "swr";
import "./App.css";

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

  // fetch data
  const { data, error } = useSWR(
    "https://jsonplaceholder.typicode.com/todos/1",
    fetcher
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  // render data
  return (
    <div className="App">
      <h2>{data.title}</h2>
      <p>UserId: {data.userId}</p>
      <p>Id: {data.id}</p>
      {data.completed? <p>Completed</p> : <p>Not Completed</p>}
    </div>
  );
}

export default App;

We can run npm start to test our app, and it should display the data correctly in the browser:

image.png

Conclusion

In this article, we discussed some of the features why SWR and the useSWR Hook can be a great choice for data fetching in React. Its caching, pagination and auto refetching can enhance user experience. It is lightweight and backend agnostic, which allows fetching data from any kind of API or database quickly and easily.

Thank you for reading, I hope it has been a useful introduction to SWR and how to use it in your React apps. Cheers!

Did you find this article valuable?

Support Victoria Lo by becoming a sponsor. Any amount is appreciated!

ย