SWR: React Hooks for Data Fetching

2.4.1 · active · verified Sun Apr 19

SWR is a lightweight and performant React Hooks library for remote data fetching, currently at version 2.4.1. It implements the 'stale-while-revalidate' cache invalidation strategy, popularized by HTTP RFC 5861, to provide an always-fresh and responsive user interface. Maintained by Vercel, SWR ensures components receive a continuous stream of data updates automatically. It offers robust features like built-in caching, request deduplication, real-time revalidation on focus/network recovery, polling, pagination, local mutation for optimistic UI, smart error retry, and comprehensive TypeScript support. Its predictable release cadence, with frequent minor updates and patches, ensures ongoing stability and feature enhancements. Key differentiators include its simplicity with a single `useSWR` hook, strong focus on performance and developer experience, and broad support for modern React features like Suspense.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic data fetching using `useSWR` with a custom `fetcher` function, handling loading and error states for a user profile.

import useSWR from 'swr';

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

function UserProfile() {
  // In a real application, you might use an environment variable for the base URL
  const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? 'https://api.example.com';
  const userId = '123'; // Example user ID
  const { data, error, isLoading } = useSWR(`${API_BASE_URL}/users/${userId}`, fetcher);

  if (error) return <div>Failed to load user data: {error.message}</div>;
  if (isLoading) return <div>Loading user profile...</div>;
  
  return (
    <div>
      <h1>User Profile</h1>
      <p>Name: {data.name}</p>
      <p>Email: {data.email}</p>
    </div>
  );
}

// Example of how to render it (e.g., in a React component tree)
// function App() {
//   return <UserProfile />;
// }
// export default App;

view raw JSON →