types.ts
Overview
The types.ts file is a core TypeScript declaration module within the SWR (stale-while-revalidate) data fetching library ecosystem. It primarily defines the comprehensive type system and interfaces that underpin SWR’s behavior, configuration options, and internal state management. This file establishes the shapes and contracts for:
Global state management and caching
Fetcher functions and responses
SWR hooks and middleware signatures
Configuration options (public and internal)
Mutator functions and mutation options
Revalidation mechanisms and events
Cache interface and state representations
By defining these types, types.ts enables strong typing and IntelliSense support throughout the SWR codebase and for library users integrating SWR with TypeScript.
Detailed Descriptions
Type Aliases and Utility Types
GlobalState
type GlobalState = [
Record<string, RevalidateCallback[]>, // EVENT_REVALIDATORS
Record<string, [number, number]>, // MUTATION timestamps: [start_ts, end_ts]
Record<string, [any, number]>, // FETCH cache: [data, timestamp]
Record<string, FetcherResponse<any>>, // PRELOAD cache
ScopedMutator, // Mutator function for updating cache
(key: string, value: any, prev: any) => void, // Setter function for cache updates
(key: string, callback: (current: any, prev: any) => void) => () => void // Subscriber to cache changes
]
Purpose: Represents the internal global state tuple used by SWR to track event revalidators, mutation timestamps, fetch cache, preload cache, mutator logic, setters, and subscribers.
Usage: Used internally in SWR to maintain and synchronize state across data keys.
FetcherResponse<Data = unknown>
type FetcherResponse<Data = unknown> = Data | Promise<Data>
Represents either synchronous data or a Promise resolving to data returned by a fetcher function.
BareFetcher<Data = unknown>
type BareFetcher<Data = unknown> = (...args: any[]) => FetcherResponse<Data>
Signature of a fetcher function that accepts any arguments and returns either data or a Promise of data.
Fetcher<Data = unknown, SWRKey extends Key = Key>
A conditional type that infers the fetcher's argument type based on the SWR key.
If the key is a function returning an argument, the fetcher accepts that argument.
If the key is
null,undefined, orfalse, fetcher isnever.Otherwise, fetcher accepts the key as argument.
BlockingData<Data, Options>
Determines if data loading should block (e.g., React Suspense mode):
Checks global and local suspense flags.
Returns
trueif suspense or fallback data is enabled.Returns
falseotherwise.
Interfaces
InternalConfiguration
interface InternalConfiguration {
cache: Cache
mutate: ScopedMutator
}
Internal-only configuration for managing cache and mutation logic.
PublicConfiguration<Data, Error, Fn>
Defines all user-exposed configuration options for SWR hooks.
Key properties include:
errorRetryInterval (number): Time between retries on error (default 5000ms).
errorRetryCount (number): Max retry attempts.
loadingTimeout (number): Timeout to trigger loading slow event (default 3000ms).
focusThrottleInterval (number): Throttling interval for focus revalidation (default 5000ms).
dedupingInterval (number): Interval to deduplicate requests (default 2000ms).
refreshInterval (number | function): Polling interval or function returning interval.
refreshWhenHidden (boolean): Poll even if window is hidden (default false).
refreshWhenOffline (boolean): Poll when offline.
revalidateOnFocus (boolean): Auto revalidate on window focus (default true).
revalidateOnReconnect (boolean): Auto revalidate on network reconnect (default true).
revalidateOnMount (boolean): Revalidate when component mounts.
revalidateIfStale (boolean): Revalidate even if data is stale (default true).
shouldRetryOnError (boolean | function): Retry on fetch errors.
keepPreviousData (boolean): Keep data when key changes.
suspense (boolean): Enable React Suspense mode (experimental).
fallbackData (Data | Promise): Initial data per hook.
fetcher (Fn): Fetcher function.
use (Middleware[]): Middleware array to extend SWR.
fallback (object): Key-value fallback data for pre-rendering.
isPaused (): Function to pause revalidations.
onLoadingSlow, onSuccess, onError, onErrorRetry, onDiscarded: Lifecycle callbacks.
compare (function): Custom comparison function to detect data changes.
isOnline, isVisible (): Functions to determine app activity state.
Example usage:
const config: PublicConfiguration<User, Error> = {
errorRetryInterval: 5000,
revalidateOnFocus: true,
fetcher: (url) => fetch(url).then(res => res.json()),
onError: (err, key) => console.error(`Error fetching ${key}`, err),
}
FullConfiguration<Data, Error, Fn>
Combines internal and public configurations.
ProviderConfiguration
Configuration related to event initialization:
initFocus(callback): Registers focus event listener and returns cleanup.initReconnect(callback): Registers reconnect event listener and returns cleanup.
SWRHook
The generic function type signature of the useSWR hook.
Supports multiple overloads:
Key only
Key + fetcher
Key + config
Key + fetcher + config
Returns an
SWRResponseobject.
Example usage:
const { data, error, mutate } = useSWR<User>('api/user', fetcher, { suspense: true })
Middleware
A higher-order function that wraps an SWRHook to extend or modify its behavior.
Signature:
type Middleware = (
useSWRNext: SWRHook
) => <Data, Error>(
key: Key,
fetcher: BareFetcher<Data> | null,
config: SWRConfiguration<Data, Error, BareFetcher<Data>>
) => SWRResponse<Data, Error>
Key and Arguments Types
Arguments: A union representing valid SWR keys: string, tuple, object, null, undefined, false.Key: EitherArgumentsor a function returningArguments.StrictTupleKeyandStrictKey: Narrower types used internally.
Mutator Types and Interfaces
MutatorCallback<Data>: Callback that receives current data and returns new data or Promise.MutatorOptions: Options controlling mutation behavior, such as revalidation, optimistic updates, rollback, etc.MutatorFn<Data>: Function signature for mutating cache: accepts cache, key, new data or callback, options.ScopedMutator: Overloaded function type for mutating one or many keys matching a predicate.KeyedMutator<Data>: Function signature for mutating a specific key's cache.
SWRConfiguration
Partial configuration type combining PublicConfiguration and ProviderConfiguration with optional provider override.
SWRResponse<Data, Error, Config>
The return type of useSWR hook, containing:
data: The fetched data or undefined.error: Error encountered or undefined.mutate: A keyed mutator function.isValidating: Boolean indicating if request is in progress.isLoading: Boolean or conditional type indicating loading state.
Revalidation Types
RevalidatorOptions: Options for revalidation calls (retry count, deduplication).Revalidator: Function signature for revalidation.RevalidateEvent: Enum of revalidation event types (focus, reconnect, mutate, error).RevalidateCallback: Callback invoked on revalidation events.
Cache<Data>
Interface for cache implementations managing SWR state:
keys(): Iterable iterator of all cache keys.get(key): Return state associated with key.set(key, value): Set state for key.delete(key): Remove key from cache.
State<Data, Error>
Represents cached state per key:
Optional
dataOptional
errorOptional
isValidatingOptional
isLoading
Important Implementation Details and Algorithms
The file defines sophisticated generic types that enable strong inference between keys, fetchers, and returned data.
Uses conditional and mapped types extensively to provide flexibility and type safety.
Supports React Suspense mode by controlling blocking of data loading.
Supports mutation with optimistic updates and rollback on errors.
Supports middleware extensibility by wrapping the SWR hook.
The global state maintains multiple caches and event subscriptions for efficient updates and deduplication.
Revalidation events and callbacks are well-typed to handle different lifecycle events precisely.
Interaction with Other Parts of the System
This file is a foundational dependency for core SWR modules (e.g., the main
useSWRhook implementation, cache management, mutation logic).It imports types from internal modules (
../indexand./events) to link with global configuration and event constants.The defined types ensure consistent usage across the SWR codebase and provide the public API contract for consumers.
Middleware, mutators, and provider configurations defined here are consumed by higher-level SWR logic for extensibility and customization.
Cache interface defined here can be implemented by various storage backends (in-memory, localStorage, etc.).
Revalidation and event types integrate with event handlers that trigger refreshes based on user focus, connectivity, and mutations.
Visual Diagram: Type Structure Flowchart
flowchart TD
A[GlobalState] -->|uses| B[RevalidateCallback[]]
A --> C[Mutation Timestamps]
A --> D[Fetch Cache]
A --> E[Preload Cache]
A --> F[ScopedMutator]
A --> G[Setter Function]
A --> H[Subscriber Function]
SWRHook -->|returns| SWRResponse
SWRResponse -->|contains| data[Data]
SWRResponse --> error[Error]
SWRResponse --> mutate[KeyedMutator]
SWRResponse --> isValidating[boolean]
SWRResponse --> isLoading[boolean]
PublicConfig -->|includes| errorRetryInterval
PublicConfig --> revalidateOnFocus
PublicConfig --> fetcher
PublicConfig --> use[Middleware[]]
PublicConfig --> onErrorRetry
MutatorOptions -->|controls| mutateBehavior[Mutation Behavior]
ScopedMutator -->|overloads| mutatorSingle[Single Key]
ScopedMutator --> mutatorMultiple[Multiple Keys]
CacheInterface -->|defines| keysMethod
CacheInterface --> getMethod
CacheInterface --> setMethod
CacheInterface --> deleteMethod
Middleware -->|wraps| SWRHook
Key -->|argument for| Fetcher
Fetcher -->|returns| FetcherResponse
SWRConfiguration -->|extends| PublicConfig
SWRConfiguration --> ProviderConfig
RevalidateCallback -->|handles| RevalidateEvents
style SWRHook fill:#f9f,stroke:#333,stroke-width:1px
style PublicConfig fill:#bbf,stroke:#333,stroke-width:1px
style ScopedMutator fill:#bfb,stroke:#333,stroke-width:1px
style CacheInterface fill:#fbf,stroke:#333,stroke-width:1px
Summary
The types.ts file is a comprehensive declaration module that defines the core types, interfaces, and contracts for SWR's data fetching and caching mechanism. It provides a strongly typed foundation for:
Cache state and mutation management
Fetcher and SWR hook signatures
Configuration options (both public and internal)
Middleware and event handling
Mutation and revalidation workflows
Its types enable modularity, extensibility, and robust type safety across the SWR library and its consumers, facilitating advanced features such as suspense mode, optimistic updates, and custom revalidation logic.