How to Implement SWR Library in React

This article provides a straightforward guide on how to integrate the SWR (Stale-While-Revalidate) library into a React application. You will learn how to install the package, create a fetcher function, use the useSWR hook to retrieve data, and handle loading and error states. By the end of this guide, you will be able to implement efficient data caching and real-time synchronization in your React components.

What is SWR?

SWR is a lightweight React Hooks library for data fetching developed by Vercel. The name “SWR” stands for Stale-While-Revalidate, a HTTP cache invalidation strategy. SWR first returns the data from the cache (stale), then sends the fetch request (revalidate), and finally comes with the up-to-date data. It provides out-of-the-box support for caching, revalidation, focus tracking, and refetching on interval.

Step 1: Install SWR

To get started, you need to install the swr package in your React project. Run one of the following commands in your terminal:

Using npm:

npm install swr

Using yarn:

yarn add swr

Step 2: Create a Fetcher Function

SWR requires a fetcher function, which is an asynchronous function that accepts a URL, fetches the data, and returns a promise. You can use the native fetch API or libraries like axios.

Here is a standard fetcher function using the native Fetch API:

const fetcher = async (url) => {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error('An error occurred while fetching the data.');
  }
  return response.json();
};

Step 3: Implement the useSWR Hook

The useSWR hook accepts two primary arguments: a unique key (usually the API URL) and the fetcher function. It returns three values: data, error, and isLoading.

Here is a complete example of how to implement SWR in a React component:

import React from 'react';
import useSWR from 'swr';

// Define the fetcher function
const fetcher = (url) => fetch(url).then((res) => res.json());

function UserProfile() {
  // Call the useSWR hook
  const { data, error, isLoading } = useSWR(
    'https://jsonplaceholder.typicode.com/users/1',
    fetcher
  );

  // Handle loading state
  if (isLoading) return <div>Loading user profile...</div>;

  // Handle error state
  if (error) return <div>Failed to load user data.</div>;

  // Render the fetched data
  return (
    <div>
      <h1>{data.name}</h1>
      <p>Email: {data.email}</p>
      <p>Company: {data.company.name}</p>
    </div>
  );
}

export default UserProfile;

Key SWR Features Utilized Automatically

By implementing the code above, your React application immediately benefits from several built-in SWR features: