React Hooks library for remote data fetching with stale-while-revalidate caching strategy
npx @tessl/cli install tessl/npm-swr@2.3.00
# SWR
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: swr
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install swr`
10
11
## Core Imports
12
13
```typescript
14
import useSWR, { SWRConfig, useSWRConfig, mutate, preload } from "swr";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const useSWR = require("swr");
21
const { SWRConfig, useSWRConfig, mutate, preload } = require("swr");
22
```
23
24
Specialized modules:
25
26
```typescript
27
import useSWRInfinite from "swr/infinite";
28
import useSWRImmutable from "swr/immutable";
29
import useSWRSubscription from "swr/subscription";
30
import useSWRMutation from "swr/mutation";
31
```
32
33
## Basic Usage
34
35
```typescript
36
import useSWR from "swr";
37
38
// Fetcher function
39
const fetcher = (url: string) => fetch(url).then((res) => res.json());
40
41
function Profile() {
42
const { data, error, isLoading } = useSWR("/api/user", fetcher);
43
44
if (error) return <div>Failed to load</div>;
45
if (isLoading) return <div>Loading...</div>;
46
return <div>Hello {data.name}!</div>;
47
}
48
```
49
50
## Architecture
51
52
SWR is built around several key concepts:
53
54
- **Stale-While-Revalidate**: Returns cached data first (stale), then fetches fresh data (revalidate)
55
- **Global State**: Shares cache and state across components automatically
56
- **Request Deduplication**: Multiple components using same key trigger only one request
57
- **Focus/Network Revalidation**: Automatically revalidates on window focus and network recovery
58
- **Middleware System**: Extensible architecture for custom behavior and specialized use cases
59
60
## Capabilities
61
62
### Core Data Fetching
63
64
Primary hook for data fetching with caching, revalidation, and error handling. Supports TypeScript generics for type-safe data access.
65
66
```typescript { .api }
67
function useSWR<Data = any, Error = any>(
68
key: Key,
69
fetcher?: Fetcher<Data, Key> | null,
70
config?: SWRConfiguration<Data, Error>
71
): SWRResponse<Data, Error>;
72
73
type Key = string | any[] | object | (() => string | any[] | object | null | undefined | false) | null | undefined | false;
74
75
interface SWRResponse<Data, Error> {
76
data: Data | undefined;
77
error: Error | undefined;
78
mutate: KeyedMutator<Data>;
79
isValidating: boolean;
80
isLoading: boolean;
81
}
82
```
83
84
[Core Data Fetching](./core-data-fetching.md)
85
86
### Global Configuration
87
88
Provider component for configuring SWR behavior globally across the application.
89
90
```typescript { .api }
91
interface SWRConfig {
92
(props: {
93
value?: Partial<SWRConfiguration>;
94
children: React.ReactNode;
95
}): JSX.Element;
96
defaultValue: SWRConfiguration;
97
}
98
```
99
100
[Global Configuration](./global-configuration.md)
101
102
### Infinite Loading
103
104
Hook for pagination and infinite loading scenarios with automatic page management.
105
106
```typescript { .api }
107
function useSWRInfinite<Data = any, Error = any>(
108
getKey: SWRInfiniteKeyLoader<Data>,
109
fetcher?: SWRInfiniteFetcher<Data> | null,
110
config?: SWRInfiniteConfiguration<Data, Error>
111
): SWRInfiniteResponse<Data, Error>;
112
113
interface SWRInfiniteResponse<Data, Error> {
114
data: Data[] | undefined;
115
error: Error | undefined;
116
mutate: SWRInfiniteKeyedMutator<Data>;
117
size: number;
118
setSize: (size: number | ((size: number) => number)) => Promise<Data[] | undefined>;
119
isValidating: boolean;
120
isLoading: boolean;
121
}
122
```
123
124
[Infinite Loading](./infinite-loading.md)
125
126
### Immutable Data
127
128
Hook for static data that doesn't require revalidation, with all revalidation options disabled.
129
130
```typescript { .api }
131
function useSWRImmutable<Data = any, Error = any>(
132
key: Key,
133
fetcher?: Fetcher<Data, Key> | null,
134
config?: SWRConfiguration<Data, Error>
135
): SWRResponse<Data, Error>;
136
```
137
138
[Immutable Data](./immutable-data.md)
139
140
### Real-time Subscriptions
141
142
Hook for real-time data updates through WebSockets, Server-Sent Events, or other subscription mechanisms.
143
144
```typescript { .api }
145
function useSWRSubscription<Data = any, Error = any>(
146
key: Key,
147
subscribe: SWRSubscription<Key, Data, Error>,
148
config?: SWRConfiguration<Data, Error>
149
): SWRSubscriptionResponse<Data, Error>;
150
151
interface SWRSubscriptionResponse<Data, Error> {
152
data?: Data;
153
error?: Error;
154
}
155
```
156
157
[Real-time Subscriptions](./subscriptions.md)
158
159
### Remote Mutations
160
161
Hook for handling remote mutations (POST, PUT, DELETE, PATCH) with optimistic updates and rollback support.
162
163
```typescript { .api }
164
function useSWRMutation<Data = any, Error = any, ExtraArg = never>(
165
key: Key,
166
fetcher: MutationFetcher<Data, Key, ExtraArg>,
167
config?: SWRMutationConfiguration<Data, Error, Key, ExtraArg>
168
): SWRMutationResponse<Data, Error, Key, ExtraArg>;
169
170
interface SWRMutationResponse<Data, Error, Key, ExtraArg> {
171
data: Data | undefined;
172
error: Error | undefined;
173
trigger: (arg: ExtraArg, options?: SWRMutationConfiguration<Data, Error, Key, ExtraArg>) => Promise<Data | undefined>;
174
reset: () => void;
175
isMutating: boolean;
176
}
177
```
178
179
[Remote Mutations](./mutations.md)
180
181
### Cache Management
182
183
Global functions for programmatic cache manipulation and data preloading.
184
185
```typescript { .api }
186
function mutate<Data = any>(
187
key: Key,
188
data?: Data | Promise<Data> | MutatorCallback<Data>,
189
options?: boolean | MutatorOptions<Data>
190
): Promise<Data | undefined>;
191
192
function preload<Data = any>(
193
key: Key,
194
fetcher: Fetcher<Data, Key>
195
): Data;
196
197
function unstable_serialize(key: Key): string | undefined;
198
```
199
200
[Cache Management](./cache-management.md)
201
202
## Types
203
204
### Core Configuration Types
205
206
```typescript { .api }
207
interface SWRConfiguration<Data = any, Error = any> {
208
errorRetryInterval?: number;
209
errorRetryCount?: number;
210
loadingTimeout?: number;
211
focusThrottleInterval?: number;
212
dedupingInterval?: number;
213
refreshInterval?: number;
214
refreshWhenHidden?: boolean;
215
refreshWhenOffline?: boolean;
216
revalidateOnFocus?: boolean;
217
revalidateOnMount?: boolean;
218
revalidateOnReconnect?: boolean;
219
revalidateIfStale?: boolean;
220
shouldRetryOnError?: boolean | ((err: Error) => boolean);
221
suspense?: boolean;
222
fallbackData?: Data;
223
keepPreviousData?: boolean;
224
compare?: (a: Data | undefined, b: Data | undefined) => boolean;
225
isPaused?: () => boolean;
226
use?: Middleware[];
227
onSuccess?: (data: Data, key: string, config: SWRConfiguration<Data, Error>) => void;
228
onError?: (err: Error, key: string, config: SWRConfiguration<Data, Error>) => void;
229
onErrorRetry?: (err: Error, key: string, config: SWRConfiguration<Data, Error>, revalidate: Revalidator, revalidateOpts: Required<RevalidatorOptions>) => void;
230
onLoadingSlow?: (key: string, config: SWRConfiguration<Data, Error>) => void;
231
fetcher?: Fetcher<Data, Key> | null;
232
}
233
234
type Fetcher<Data, SWRKey extends Key> = SWRKey extends () => infer Arg | null | undefined | false
235
? (arg: Arg) => Data | Promise<Data>
236
: SWRKey extends null | undefined | false
237
? never
238
: SWRKey extends infer Arg
239
? (arg: Arg) => Data | Promise<Data>
240
: never;
241
242
interface KeyedMutator<Data> {
243
(data?: Data | Promise<Data> | MutatorCallback<Data>, options?: boolean | MutatorOptions<Data>): Promise<Data | undefined>;
244
}
245
246
interface MutatorOptions<Data = any> {
247
revalidate?: boolean;
248
populateCache?: boolean | ((result: Data, currentData: Data | undefined) => Data);
249
optimisticData?: Data | ((currentData: Data | undefined) => Data);
250
rollbackOnError?: boolean | ((error: any) => boolean);
251
}
252
253
type MutatorCallback<Data> = (currentData: Data | undefined) => Data | undefined;
254
255
interface SWRGlobalConfig {
256
// Extension point for global configuration options
257
}
258
```