CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-swr

React Hooks library for remote data fetching with stale-while-revalidate caching strategy

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

SWR

SWR is a React Hooks library for data fetching that implements the stale-while-revalidate caching strategy. It provides fast, lightweight, and reusable data fetching capabilities with built-in caching, request deduplication, and real-time updates.

Package Information

  • Package Name: swr
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install swr

Core Imports

import useSWR, { SWRConfig, useSWRConfig, mutate, preload } from "swr";

For CommonJS:

const useSWR = require("swr");
const { SWRConfig, useSWRConfig, mutate, preload } = require("swr");

Specialized modules:

import useSWRInfinite from "swr/infinite";
import useSWRImmutable from "swr/immutable";
import useSWRSubscription from "swr/subscription";
import useSWRMutation from "swr/mutation";

Basic Usage

import useSWR from "swr";

// Fetcher function
const fetcher = (url: string) => fetch(url).then((res) => res.json());

function Profile() {
  const { data, error, isLoading } = useSWR("/api/user", fetcher);

  if (error) return <div>Failed to load</div>;
  if (isLoading) return <div>Loading...</div>;
  return <div>Hello {data.name}!</div>;
}

Architecture

SWR is built around several key concepts:

  • Stale-While-Revalidate: Returns cached data first (stale), then fetches fresh data (revalidate)
  • Global State: Shares cache and state across components automatically
  • Request Deduplication: Multiple components using same key trigger only one request
  • Focus/Network Revalidation: Automatically revalidates on window focus and network recovery
  • Middleware System: Extensible architecture for custom behavior and specialized use cases

Capabilities

Core Data Fetching

Primary hook for data fetching with caching, revalidation, and error handling. Supports TypeScript generics for type-safe data access.

function useSWR<Data = any, Error = any>(
  key: Key,
  fetcher?: Fetcher<Data, Key> | null,
  config?: SWRConfiguration<Data, Error>
): SWRResponse<Data, Error>;

type Key = string | any[] | object | (() => string | any[] | object | null | undefined | false) | null | undefined | false;

interface SWRResponse<Data, Error> {
  data: Data | undefined;
  error: Error | undefined;
  mutate: KeyedMutator<Data>;
  isValidating: boolean;
  isLoading: boolean;
}

Core Data Fetching

Global Configuration

Provider component for configuring SWR behavior globally across the application.

interface SWRConfig {
  (props: {
    value?: Partial<SWRConfiguration>;
    children: React.ReactNode;
  }): JSX.Element;
  defaultValue: SWRConfiguration;
}

Global Configuration

Infinite Loading

Hook for pagination and infinite loading scenarios with automatic page management.

function useSWRInfinite<Data = any, Error = any>(
  getKey: SWRInfiniteKeyLoader<Data>,
  fetcher?: SWRInfiniteFetcher<Data> | null,
  config?: SWRInfiniteConfiguration<Data, Error>
): SWRInfiniteResponse<Data, Error>;

interface SWRInfiniteResponse<Data, Error> {
  data: Data[] | undefined;
  error: Error | undefined;
  mutate: SWRInfiniteKeyedMutator<Data>;
  size: number;
  setSize: (size: number | ((size: number) => number)) => Promise<Data[] | undefined>;
  isValidating: boolean;
  isLoading: boolean;
}

Infinite Loading

Immutable Data

Hook for static data that doesn't require revalidation, with all revalidation options disabled.

function useSWRImmutable<Data = any, Error = any>(
  key: Key,
  fetcher?: Fetcher<Data, Key> | null,
  config?: SWRConfiguration<Data, Error>
): SWRResponse<Data, Error>;

Immutable Data

Real-time Subscriptions

Hook for real-time data updates through WebSockets, Server-Sent Events, or other subscription mechanisms.

function useSWRSubscription<Data = any, Error = any>(
  key: Key,
  subscribe: SWRSubscription<Key, Data, Error>,
  config?: SWRConfiguration<Data, Error>
): SWRSubscriptionResponse<Data, Error>;

interface SWRSubscriptionResponse<Data, Error> {
  data?: Data;
  error?: Error;
}

Real-time Subscriptions

Remote Mutations

Hook for handling remote mutations (POST, PUT, DELETE, PATCH) with optimistic updates and rollback support.

function useSWRMutation<Data = any, Error = any, ExtraArg = never>(
  key: Key,
  fetcher: MutationFetcher<Data, Key, ExtraArg>,
  config?: SWRMutationConfiguration<Data, Error, Key, ExtraArg>
): SWRMutationResponse<Data, Error, Key, ExtraArg>;

interface SWRMutationResponse<Data, Error, Key, ExtraArg> {
  data: Data | undefined;
  error: Error | undefined;
  trigger: (arg: ExtraArg, options?: SWRMutationConfiguration<Data, Error, Key, ExtraArg>) => Promise<Data | undefined>;
  reset: () => void;
  isMutating: boolean;
}

Remote Mutations

Cache Management

Global functions for programmatic cache manipulation and data preloading.

function mutate<Data = any>(
  key: Key,
  data?: Data | Promise<Data> | MutatorCallback<Data>,
  options?: boolean | MutatorOptions<Data>
): Promise<Data | undefined>;

function preload<Data = any>(
  key: Key,
  fetcher: Fetcher<Data, Key>
): Data;

function unstable_serialize(key: Key): string | undefined;

Cache Management

Types

Core Configuration Types

interface SWRConfiguration<Data = any, Error = any> {
  errorRetryInterval?: number;
  errorRetryCount?: number;
  loadingTimeout?: number;
  focusThrottleInterval?: number;
  dedupingInterval?: number;
  refreshInterval?: number;
  refreshWhenHidden?: boolean;
  refreshWhenOffline?: boolean;
  revalidateOnFocus?: boolean;
  revalidateOnMount?: boolean;
  revalidateOnReconnect?: boolean;
  revalidateIfStale?: boolean;
  shouldRetryOnError?: boolean | ((err: Error) => boolean);
  suspense?: boolean;
  fallbackData?: Data;
  keepPreviousData?: boolean;
  compare?: (a: Data | undefined, b: Data | undefined) => boolean;
  isPaused?: () => boolean;
  use?: Middleware[];
  onSuccess?: (data: Data, key: string, config: SWRConfiguration<Data, Error>) => void;
  onError?: (err: Error, key: string, config: SWRConfiguration<Data, Error>) => void;
  onErrorRetry?: (err: Error, key: string, config: SWRConfiguration<Data, Error>, revalidate: Revalidator, revalidateOpts: Required<RevalidatorOptions>) => void;
  onLoadingSlow?: (key: string, config: SWRConfiguration<Data, Error>) => void;
  fetcher?: Fetcher<Data, Key> | null;
}

type Fetcher<Data, SWRKey extends Key> = SWRKey extends () => infer Arg | null | undefined | false
  ? (arg: Arg) => Data | Promise<Data>
  : SWRKey extends null | undefined | false
  ? never
  : SWRKey extends infer Arg
  ? (arg: Arg) => Data | Promise<Data>
  : never;

interface KeyedMutator<Data> {
  (data?: Data | Promise<Data> | MutatorCallback<Data>, options?: boolean | MutatorOptions<Data>): Promise<Data | undefined>;
}

interface MutatorOptions<Data = any> {
  revalidate?: boolean;
  populateCache?: boolean | ((result: Data, currentData: Data | undefined) => Data);
  optimisticData?: Data | ((currentData: Data | undefined) => Data);
  rollbackOnError?: boolean | ((error: any) => boolean);
}

type MutatorCallback<Data> = (currentData: Data | undefined) => Data | undefined;

interface SWRGlobalConfig {
  // Extension point for global configuration options
}

docs

cache-management.md

core-data-fetching.md

global-configuration.md

immutable-data.md

index.md

infinite-loading.md

mutations.md

subscriptions.md

tile.json