Skip to main content

Command Palette

Search for a command to run...

Fetching Data in React with SWR (Stale While Revalidate)

Published
3 min read
Fetching Data in React with SWR (Stale While Revalidate)
O

I am a front end developer and technical blogger at ebuntoday.hashnode.dev. I write to help new developers find their path to becoming better in their fields. Writing also keeps me abreast at each point in time. I am opened to constructive feedback,as this will go a long way in my growth. In case, you enjoy reading my articles and find any of them helpful, please like and share .

SWR is one of the coolest ways to fetch data in React. The name stands for Stale While Revalidate, which describes its strategy — it returns cached (stale) data first, then revalidates it by fetching fresh data in the background.

It’s both a strategy and a library, designed to make data fetching, caching, and revalidation easier and more efficient. One great thing about SWR is that it removes the need for manual state and effect management — everything is built in.

  1. Setting Up SWR

    To get started, install the SWR package:

     npm install swr
     # or
     yarn add swr
    

    Then, import the useSWR hook into your component:

     import useSWR from 'swr';
    

    You’ll also need a fetcher function — this tells SWR how to fetch and transform your data. You can use the Fetch API or even Axios.

    Here’s a basic setup using the Fetch API:

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

    Using SWR in a React Component

    Let’s use useSWR to fetch and display data:

     import React from "react";
     import useSWR from "swr";
    
     const fetcher = (...args) => fetch(...args).then(res => res.json());
    
     function SwrExample() {
       const { data, error } = useSWR("https://dog.ceo/api/breeds/image/random", fetcher, {
         suspense: true,
       });
    
       if (error) return <h1>There was an error!</h1>;
    
       return (
         <div>
           <img width={500} src={data?.message} alt="Random Dog" />
         </div>
       );
     }
    
     export default SwrExample;
    

    How It Works

    • The first argument (url) is your API endpoint.

    • The second argument (fetcher) defines how to fetch and parse data.

    • SWR takes care of managing the internal state, revalidation, and caching.

    • You don’t need to create a useState or useEffect: Everything is handled automatically.

If your data hasn’t arrived yet, it may temporarily be null. To avoid errors when accessing properties on null, you can use optional chaining (data?.message). This ensures that your code won’t break while the data is still loading.

Using Suspense for Loading States

React’s Suspense component pairs beautifully with SWR.
To use it, set suspense: true in your SWR options, then wrap your component with <Suspense>:

    import React, { Suspense } from "react";
    import SwrExample from "./SwrExample";

    function App() {
      return (
        <Suspense fallback={<h2>Loading...</h2>}>
          <SwrExample />
        </Suspense>
      );
    }

    export default App;

With this setup:

  • While the data is loading, the fallback (<h2>Loading...</h2>) is displayed.

  • If there’s an error, your component handles it gracefully.

  • Once the data loads, the actual UI appears.

Why Use SWR?

Even though we’re still fetching data with something like the Fetch API or Axios, SWR handles everything else — caching, revalidation, and synchronization — automatically.

This means:

  • No manual useState or useEffect.

  • Instant UI updates with cached data.

  • Automatic background revalidation for fresh results.

  • Built-in error and loading handling (with Suspense).

💡 Pro tip:
SWR isn’t just a data-fetching library. it’s a data management strategy that helps your app stay fast, consistent, and always up to date.

Wrapping Up

SWR takes the stress out of data fetching by combining simplicity with smart caching. It’s like having React Query’s power but with a lighter setup and a focus on revalidation and speed.

If you’ve ever found yourself writing too many useEffect and useState Hooks just to manage API data, SWR is worth exploring. It keeps your code clean, your UI fast, and your data always fresh.

Thank you for reading!✨🎉👏
Have you tried using SWR before, or are you just hearing about it for the first time?
I’d love to hear your thoughts in the comments below 🚀

Fetching Data in React with SWR (Stale While Revalidate)