config.ts
Overview
The config.ts file defines the default configuration, core utilities, and retry logic for the SWR (stale-while-revalidate) data fetching library. It establishes:
The default cache provider and mutation mechanism.
A configurable retry strategy for handling fetch errors with exponential backoff.
The consolidated default configuration object used throughout the SWR system.
Core helpers such as deep equality comparison.
This file is central to SWR's internal behavior, providing default implementations and utilities that other modules and hooks depend on for consistent, robust data fetching, caching, and error recovery.
Detailed Explanation of Entities
1. onErrorRetry Function
const onErrorRetry = (
_: unknown,
__: string,
config: Readonly<PublicConfiguration>,
revalidate: Revalidator,
opts: Required<RevalidatorOptions>
): void => { ... }
Purpose
Handles automatic retry attempts on data fetch errors, implementing an exponential backoff retry strategy with jitter. It schedules retry attempts up to a configurable maximum retry count.
Parameters
_:unknown— The error object (unused in this function).__:string— The key corresponding to the resource being fetched (unused here).config:Readonly<PublicConfiguration>— The SWR configuration object, including retry-related settings.revalidate:Revalidator— A callback function to re-trigger data fetching/revalidation.opts:Required<RevalidatorOptions>— Options object containing retry count and other flags.
Return Value
void
Implementation Details
Reads
errorRetryCountand currentretryCountfrom config and options.Calculates a retry delay using exponential backoff capped at 2^8 and multiplied by
errorRetryInterval.Adds a random factor (between 0.5 and 1.5) to avoid synchronized retries (thundering herd problem).
Aborts retry scheduling if retry count exceeds the maximum.
Uses
setTimeoutto schedule therevalidatecall with the calculated delay.
Usage Example
// Automatically invoked by SWR internals on fetch error
onErrorRetry(
fetchError,
resourceKey,
swrConfig,
() => mutate(resourceKey), // revalidate callback
{ retryCount: currentRetryCount }
);
2. compare
const compare = dequal
Purpose
Provides a deep equality comparison function to determine if two values are equivalent. Used internally to avoid unnecessary re-renders or cache updates when data hasn't changed.
Imported from the lightweight
dequal/litepackage for performance.
Usage Example
if (!compare(oldData, newData)) {
// Update cache or trigger re-render
}
3. cache and mutate
const [cache, mutate] = initCache(new Map()) as [Cache<any>, ScopedMutator]
Purpose
cache: The default cache provider that stores data keyed by resource identifiers.mutate: The scoped mutator function used to update cached data and trigger revalidation.
Details
Both are initialized by
initCachewith a freshMapinstance, providing an in-memory cache.Exported for use throughout SWR as the default caching mechanism.
Can be overridden by users by supplying custom cache providers or mutation functions.
Usage Example
// Access cached data directly
const cachedData = cache.get(resourceKey)
// Trigger a cache update and revalidation
mutate(resourceKey, fetcherFunction)
4. defaultConfig
export const defaultConfig: FullConfiguration = mergeObjects(
{
// event handlers
onLoadingSlow: noop,
onSuccess: noop,
onError: noop,
onErrorRetry,
onDiscarded: noop,
// feature toggles
revalidateOnFocus: true,
revalidateOnReconnect: true,
revalidateIfStale: true,
shouldRetryOnError: true,
// timing configurations
errorRetryInterval: slowConnection ? 10000 : 5000,
focusThrottleInterval: 5 * 1000,
dedupingInterval: 2 * 1000,
loadingTimeout: slowConnection ? 5000 : 3000,
// providers and utilities
compare,
isPaused: () => false,
cache,
mutate,
fallback: {}
},
preset
)
Purpose
Defines the default configuration object used by SWR hooks and core logic. It combines:
Default event handlers (mostly no-ops except
onErrorRetry).Flags controlling automatic revalidation behavior.
Time intervals for retries, throttling, deduplication, and loading timeouts.
Core providers like the cache, mutate function, and comparison function.
A fallback data object.
Extends and overrides with additional settings from the
preset(web-specific defaults).
Important Fields
Field | Description | Default Value |
|---|---|---|
| Callback when loading is slow | No-op function |
| Callback on successful fetch | No-op function |
| Callback on fetch error | No-op function |
| Callback to handle retries on error | The exponential backoff function |
| Callback when a request is discarded | No-op function |
| Whether to revalidate when window gains focus |
|
| Revalidate on network reconnect |
|
| Revalidate when cached data is stale |
|
| Whether to retry automatically on error |
|
| Base interval for retry delay (ms) |
|
| Minimum interval between focus-based revalidations (ms) |
|
| Interval to deduplicate requests for the same key (ms) |
|
| Timeout to consider loading slow (ms) |
|
| Deep equality comparison function |
|
| Function to pause SWR (returns boolean) | Always |
| Default cache provider | In-memory |
| Default mutate function | Scoped mutator tied to cache |
| Fallback data for keys | Empty object |
Usage Example
import { defaultConfig } from './config'
const config = {
...defaultConfig,
revalidateOnFocus: false, // override
}
Important Implementation Details and Algorithms
Exponential Backoff Retry Logic in onErrorRetry
Uses bit shift operator
1 << retryCountto calculate exponential delay capped at 2^8.Adds randomness
(Math.random() + 0.5)to prevent simultaneous retries.Uses
setTimeoutto schedule the retry using the SWR revalidate function.Prevents infinite retry loops by enforcing
errorRetryCountas max retry attempts.The retry interval multiplies the exponential backoff to scale delays appropriately.
Cache Initialization
initCachecreates a cache instance based on aMap.Returns a tuple
[cache, mutate]wherecacheis the cache interface andmutateis the function to update it.Provides an abstraction over raw in-memory storage.
Configuration Merging
Uses
mergeObjectsutility to combine the base config with the platform/web-specificpreset.Ensures sensible defaults tailored for web environments while allowing customization.
Interactions with Other System Parts
Cache (
cacheandmutate): Other SWR modules usecacheto store and retrieve data, andmutateto update cache and trigger revalidation.Error Handling & Retry Logic:
onErrorRetryis part of the retry lifecycle invoked on fetch errors, interacting with the revalidation mechanisms.Web Preset (
preset): Provides defaults optimized for web browsers, merged intodefaultConfig.Shared Utilities: Functions like
isUndefined,noop, andmergeObjectsprovide common helpers used across the configuration.Comparison (
compare): Used by SWR to determine if new data differs from cached data, to avoid unnecessary updates.Environment Detection (
slowConnection): Influences timing defaults to accommodate slow networks.
Visual Diagram: File Structure and Main Functions
flowchart TD
subgraph Config Module
direction TB
onErrorRetry["onErrorRetry(error, key, config, revalidate, opts): void"]
compare["compare (deep equality function)"]
cacheMutate["[cache, mutate] = initCache(Map)"]
defaultConfig["defaultConfig: FullConfiguration"]
cacheMutate --> cache["cache (Cache<any>)"]
cacheMutate --> mutate["mutate (ScopedMutator)"]
defaultConfig --> onErrorRetry
defaultConfig --> compare
defaultConfig --> cache
defaultConfig --> mutate
defaultConfig --> preset["preset (web default config)"]
end
Summary
The config.ts module is a foundational piece of the SWR library, defining how data fetching:
Manages retries on errors with a robust, randomized exponential backoff strategy.
Stores and mutates cached data using an in-memory cache provider by default.
Applies a comprehensive set of default configuration parameters for event handling, revalidation, timing, and caching.
Provides deep equality comparison to optimize updates.
Integrates platform-specific presets to tailor default behavior.
It enables SWR to function resiliently in diverse environments with sensible defaults while allowing extensibility and customization by users.
Appendix: Key Imports and Utilities Used in config.ts
Import | Source | Purpose |
|---|---|---|
| Type definitions for config, revalidation, cache | |
| Initializes cache and mutate functions | |
| Default configuration preset for web environments | |
| Boolean indicating slow network environment | |
| Utility helpers for common operations | |
|
| Lightweight deep equality comparison function |
This documentation provides a comprehensive understanding of the config.ts file’s purpose, its internal components, their usage, and how it fits within the broader SWR architecture.