SWR : récupération de données React

VérifiéSûr

Récupérez, mettez en cache et revalidez les données dans React avec SWR, une bibliothèque légère de Vercel. Prend en charge la pagination, les mises à jour optimistes et la revalidation en arrière-plan.

Spar Skills Guide Bot
DeveloppementIntermédiaire
28/07/2026
Claude CodeCursorCopilot
#react#data-fetching#swr#caching#optimistic-updates

Recommandé pour

Synthèse automatique

Guide l'usage de SWR pour récupérer, mettre en cache et revalider des données dans React, avec mutations, pagination et mises à jour optimistes.

Points forts

  • Extraits de code directement réutilisables pour les hooks de fetch, la configuration globale et les mutations
  • Détaille les mises à jour optimistes avec optimisticData et rollbackOnError
  • Couvre la pagination et le chargement infini pilotés par la clé useSWR
  • Approche pragmatique d'une API réduite, avec les options de revalidation expliquées

Limites

  • Le contenu du fichier semble tronqué (la section « Infinite Loading » s'arrête au milieu)
  • Ne traite ni des tests, ni des error boundaries, ni de la gestion fine des erreurs
  • Suppose un fetcher basé sur fetch renvoyant du JSON et ne compare pas réellement avec TanStack Query
Quand l'utiliser

À utiliser quand un composant React doit afficher des données d'API mises en cache et rafraîchies automatiquement en arrière-plan.

Quand l'éviter

À éviter si le projet n'utilise pas React ou si vous avez besoin de fonctionnalités avancées (persistance hors ligne, devtools) propres à une bibliothèque de requêtes plus complète.

Analyse de sécurité

Sûr
Score qualité92/100

This is an educational skill about the SWR library for React data fetching. It contains standard code examples and instructions using npm install and fetch, with no destructive, exfiltrating, or obfuscated actions. There are no declared tools that would execute code, and the content poses no meaningful execution risk.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Basic hook + loading state
Add SWR to my Next.js app: create a useUser hook that fetches /api/users/[id], exposes isLoading and an error, and lets me manually revalidate.
Optimistic todo creation
Using SWR in my React app, implement optimistic updates for adding a todo with mutate, optimisticData, and rollbackOnError so the list reverts if the POST fails.
Global SWR config
Set up a global SWRConfig in my Vite React app with a shared fetcher that throws on non-OK responses, revalidateOnFocus, and a 2000ms dedupingInterval.

name: swr description: >- Fetch, cache, and revalidate data in React with SWR — stale-while-revalidate data fetching library by Vercel. Use when someone asks to "fetch data in React", "SWR", "data fetching hook", "cache API calls", "stale-while- revalidate", "auto-refresh data", or "React data fetching without Redux". Covers data fetching, caching, revalidation, mutation, pagination, and optimistic updates. license: Apache-2.0 compatibility: "React 18+. Next.js, Remix, Vite." metadata: author: terminal-skills version: "1.0.0" category: development tags: ["data-fetching", "swr", "react", "cache", "revalidation"]

SWR

Overview

SWR (stale-while-revalidate) is a React data fetching library — show cached data instantly, then revalidate in the background. Built by Vercel, it handles caching, deduplication, revalidation on focus/reconnect, pagination, and optimistic updates. Simpler than TanStack Query for straightforward data fetching, with a smaller API surface.

When to Use

  • Fetching API data in React components
  • Need instant page loads with background revalidation
  • Real-time data that should refresh automatically
  • Paginated or infinite scroll data
  • Simpler alternative to TanStack Query for most use cases

Instructions

Setup

npm install swr

Basic Data Fetching

// hooks/useUser.ts — Fetch and cache user data
import useSWR from "swr";

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

export function useUser(userId: string) {
  const { data, error, isLoading, mutate } = useSWR(
    `/api/users/${userId}`,
    fetcher,
  );

  return {
    user: data,
    isLoading,
    isError: error,
    mutate,  // Manually revalidate
  };
}

// Usage in component
function UserProfile({ userId }) {
  const { user, isLoading } = useUser(userId);
  if (isLoading) return <div>Loading...</div>;
  return <div>{user.name}</div>;
}

Global Configuration

// app/providers.tsx — Global SWR config
import { SWRConfig } from "swr";

const fetcher = async (url: string) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error("API error");
  return res.json();
};

export function Providers({ children }) {
  return (
    <SWRConfig
      value={{
        fetcher,
        revalidateOnFocus: true,      // Refresh when tab regains focus
        revalidateOnReconnect: true,   // Refresh when internet reconnects
        dedupingInterval: 2000,        // Dedupe requests within 2s
        errorRetryCount: 3,
      }}
    >
      {children}
    </SWRConfig>
  );
}

Mutation and Optimistic Updates

// components/TodoList.tsx — Optimistic updates
import useSWR, { useSWRConfig } from "swr";

function TodoList() {
  const { data: todos, mutate } = useSWR("/api/todos");

  const addTodo = async (title: string) => {
    const newTodo = { id: Date.now(), title, done: false };

    // Optimistic update — show immediately, revalidate in background
    await mutate(
      async () => {
        await fetch("/api/todos", {
          method: "POST",
          body: JSON.stringify({ title }),
        });
        // Return updated data (or let SWR refetch)
      },
      {
        optimisticData: [...(todos || []), newTodo],
        rollbackOnError: true,  // Revert if API fails
        revalidate: true,       // Refetch after mutation
      }
    );
  };
}

Pagination

// components/PostList.tsx — Paginated data
import useSWR from "swr";

function PostList() {
  const [page, setPage] = useState(1);

  const { data, isLoading } = useSWR(`/api/posts?page=${page}&limit=20`);

  return (
    <div>
      {data?.posts.map((post) => <PostCard key={post.id} post={post} />)}
      <button onClick={() => setPage(page - 1)} disabled={page <= 1}>Previous</button>
      <button onClick={() => setPage(page + 1)} disabled={!data?.hasMore}>Next</button>
    </div>
  );
}

Infinite Loading

// components/InfiniteFeed.tsx — Infinite scroll
import useSWRInfinite from "swr/infinite";

function InfiniteFeed() {
  const { data, size, setSize, isLoading } = useSWRInfinite(
    (index) => `/api/feed?page=${index + 1}&limit=20`,
  );

  const posts = data?.flatMap((page) => page.posts) || [];
  const hasMore = data?.[data.length - 1]?.hasMore;

  return (
    <div>
      {posts.map((post) => <PostCard key={post.id} post={post} />)}
      {hasMore && (
        <button onClick={() => setSize(size + 1)} disabled={isLoading}>
          Load More
        </button>
      )}
    </div>
  );
}

Examples

Example 1: Dashboard with auto-refreshing data

User prompt: "Build a dashboard that shows live metrics — refresh every 5 seconds."

The agent will use SWR with refreshInterval: 5000, show cached data instantly on mount, and handle loading/error states.

Example 2: CRUD with optimistic updates

User prompt: "Build a todo app where adding/deleting feels instant."

The agent will use SWR mutations with optimistic data, rollback on error, and automatic revalidation after changes.

Guidelines

  • Key = cache key — same key = same cached data across components
  • null key skips fetching — conditional fetching: useSWR(userId ? /api/... : null)
  • Revalidation on focus — data refreshes when user returns to tab
  • Optimistic updates — show changes immediately, revert on error
  • mutate for cache updates — bound (per-key) or global
  • useSWRInfinite for infinite scroll — accumulates pages
  • Deduplication — multiple components using same key = one request
  • Error retry built-in — automatic with exponential backoff
  • Smaller than TanStack Query — simpler API for simpler needs
  • Works with any fetcher — fetch, axios, GraphQL clients

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/swr-react-data-fetching-caching-ms47vpl1/download' --output '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md.part' && mv '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md.part' '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Environnement déclaré par l’auteur : React 18+. Next.js, Remix, Vite.

Extrait original : Setup
npm install swr

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md' && test -s '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/swr' && cp -R '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1' '.claude/skills/swr'

Cursor
test -f '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md' && test -s '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/swr' && cp -R '.skill-downloads/swr-react-data-fetching-caching-ms47vpl1' '.cursor/skills/swr'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/swr-react-data-fetching-caching-ms47vpl1'

openskills read 'swr-react-data-fetching-caching-ms47vpl1'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/swr-react-data-fetching-caching-ms47vpl1/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires