All Resources
Library
ReactData FetchingHooks
May 27, 2024

SWR Data Fetching

Stale-While-Revalidate data fetching library for React with caching and revalidation.

Overview

SWR is a React Hooks library for data fetching. It provides a simple interface for fetching, caching, and revalidating data with a focus on user experience.

Key Features

  • Smart Caching: Automatic cache management and revalidation
  • Focus Revalidation: Refetch when window regains focus
  • Polling: Built-in interval polling
  • Error Handling: Retry logic and error recovery
  • Pagination: Easy pagination support

Quick Start

npm install swr

Basic Usage

import useSWR from 'swr'

const fetcher = (url: string) => fetch(url).then(r => r.json())

export function UserProfile({ userId }: { userId: number }) {
  const { data, error, isLoading } = useSWR(
    `/api/user/${userId}`,
    fetcher
  )

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

  return <div>Welcome {data.name}</div>
}

Advanced Patterns

Conditional Fetching

const { data } = useSWR(
  shouldFetch ? `/api/user/${userId}` : null,
  fetcher
)

Dependent Requests

const { data: user } = useSWR(`/api/user/${id}`, fetcher)
const { data: posts } = useSWR(
  user ? `/api/posts?userId=${user.id}` : null,
  fetcher
)

Mutation

const { data, mutate } = useSWR('/api/user', fetcher)

async function updateName(newName: string) {
  await fetch('/api/user', { method: 'POST', body: JSON.stringify({ name: newName }) })
  mutate() // Revalidate
}

SWR handles race conditions and deduplicates requests automatically.

Curated by

Shyam