React Hooks library for remote data fetching with stale-while-revalidate caching strategy
npx @tessl/cli install tessl/npm-swr@2.3.0SWR 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.
npm install swrimport 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";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>;
}SWR is built around several key concepts:
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;
}Provider component for configuring SWR behavior globally across the application.
interface SWRConfig {
(props: {
value?: Partial<SWRConfiguration>;
children: React.ReactNode;
}): JSX.Element;
defaultValue: SWRConfiguration;
}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;
}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>;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;
}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;
}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;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
}