DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Understanding SWR (Stale-While-Revalidate) in React for Optimized Data Fetching

SWR (Stale-While-Revalidate) in React

SWR is a React hook library for data fetching that stands for "Stale-While-Revalidate." It provides an elegant and optimized solution to handle remote data fetching, caching, and revalidation. It allows you to fetch data while showing stale (cached) data from a previous request, and then revalidate the data by fetching the latest data in the background without blocking the UI. This ensures that the user sees immediate feedback while still getting fresh data.

SWR is widely used in React applications for data fetching because it provides an easy-to-use, highly efficient, and flexible solution for managing asynchronous data.


1. Key Features of SWR:

  • Stale-While-Revalidate: SWR returns the cached (stale) data while fetching the updated (revalidated) data in the background.
  • Automatic Re-fetching: SWR automatically re-fetches data in the background to keep the data up to date.
  • Built-in Caching: It caches the results of requests and uses it to return stale data instantly.
  • Request Deduplication: SWR automatically deduplicates requests, ensuring that multiple identical requests are not fired simultaneously.
  • Interval-based Polling: You can set intervals for data polling (re-fetching data at regular intervals).
  • Error Handling: It provides built-in mechanisms to handle errors and retries.
  • Pagination & Pagination Cursor Support: SWR is also useful for handling data pagination.

2. Basic Setup of SWR

To get started with SWR, you first need to install it in your React project:

npm install swr
Enter fullscreen mode Exit fullscreen mode

Once SWR is installed, you can use it in your components.


3. Example: Fetching Data Using SWR

Here’s a basic example demonstrating how to use SWR for data fetching in a React component.

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

// Function to fetch data from the API
const fetcher = (url) => fetch(url).then((res) => res.json());

const DataFetchingComponent = () => {
  // useSWR hook with the URL and fetcher function
  const { data, error, isLoading } = useSWR('https://api.example.com/data', fetcher);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Fetched Data</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default DataFetchingComponent;
Enter fullscreen mode Exit fullscreen mode

4. Explanation of the Code:

  • useSWR: This is the hook provided by the SWR library for fetching data. It accepts two arguments:

    • The key (URL in this case), which is used to identify the resource being fetched.
    • The fetcher function, which defines how to fetch the data (in this case, it uses the native fetch API to retrieve data and parse it as JSON).
  • State Variables:

    • data: Contains the response data once it’s fetched.
    • error: Stores any error message if the fetch fails.
    • isLoading: A boolean indicating whether the data is being fetched or not.
  • UI Rendering:

    • Initially, when the data is loading, the component shows a "Loading..." message.
    • If an error occurs during fetching, it displays the error message.
    • Once the data is successfully fetched, it is displayed in a list.

5. Advanced Usage: Handling Revalidation and Interval Fetching

You can take advantage of SWR’s built-in features for better control over data fetching.

Revalidation on Focus:

By default, SWR will re-fetch data when the window regains focus, ensuring that you always have the latest data when the user returns to your app.

const { data, error } = useSWR('https://api.example.com/data', fetcher, {
  revalidateOnFocus: true,
});
Enter fullscreen mode Exit fullscreen mode

Polling Interval:

You can set up polling with a re-fetch interval to keep the data fresh at regular intervals.

const { data, error } = useSWR('https://api.example.com/data', fetcher, {
  refreshInterval: 5000,  // Re-fetch every 5 seconds
});
Enter fullscreen mode Exit fullscreen mode

Error Retry:

SWR also allows you to configure how it retries failed requests.

const { data, error } = useSWR('https://api.example.com/data', fetcher, {
  errorRetryCount: 3,  // Retry the request 3 times if it fails
});
Enter fullscreen mode Exit fullscreen mode

6. Caching with SWR

SWR caches the data and returns the cached version until it revalidates it. This means that if you re-render or navigate to the component again, it will show the cached data immediately, giving the user a faster response time.

const { data, error } = useSWR('https://api.example.com/data', fetcher);

// The next time this component is rendered, SWR will serve cached data until it is revalidated.
Enter fullscreen mode Exit fullscreen mode

7. SWR with Custom Fetcher:

If you need to customize the fetching logic (e.g., adding authentication headers), you can provide a custom fetcher function.

const customFetcher = (url) =>
  fetch(url, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  }).then((res) => res.json());

const { data, error } = useSWR('https://api.example.com/data', customFetcher);
Enter fullscreen mode Exit fullscreen mode

8. SWR vs Axios & Fetch

While both Axios and Fetch are widely used for making HTTP requests, SWR is designed for handling remote data fetching with built-in caching, revalidation, and background fetching. SWR abstracts away the repetitive logic of fetching and caching data, making it more convenient and efficient in React.

  • Axios: Great for performing simple HTTP requests, but doesn't provide features like caching, background re-fetching, or automatic revalidation.
  • SWR: Focused on data fetching with caching, revalidation, and background updates to keep the UI fresh and fast.

9. Conclusion

SWR is a powerful and flexible library for managing data fetching in React. It simplifies many aspects of working with remote data, including caching, revalidation, and error handling. By using SWR, you can enhance the performance and reliability of your applications with minimal effort.


Top comments (0)