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:

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

Return Value

Implementation Details

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.

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

Details

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:

Important Fields

Field

Description

Default Value

onLoadingSlow

Callback when loading is slow

No-op function

onSuccess

Callback on successful fetch

No-op function

onError

Callback on fetch error

No-op function

onErrorRetry

Callback to handle retries on error

The exponential backoff function

onDiscarded

Callback when a request is discarded

No-op function

revalidateOnFocus

Whether to revalidate when window gains focus

true

revalidateOnReconnect

Revalidate on network reconnect

true

revalidateIfStale

Revalidate when cached data is stale

true

shouldRetryOnError

Whether to retry automatically on error

true

errorRetryInterval

Base interval for retry delay (ms)

5000 or 10000 if slow connection

focusThrottleInterval

Minimum interval between focus-based revalidations (ms)

5000

dedupingInterval

Interval to deduplicate requests for the same key (ms)

2000

loadingTimeout

Timeout to consider loading slow (ms)

3000 or 5000 if slow connection

compare

Deep equality comparison function

dequal

isPaused

Function to pause SWR (returns boolean)

Always false

cache

Default cache provider

In-memory Map cache

mutate

Default mutate function

Scoped mutator tied to cache

fallback

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

Cache Initialization

Configuration Merging


Interactions with Other System Parts


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:

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

PublicConfiguration et al.

../types

Type definitions for config, revalidation, cache

initCache

./cache

Initializes cache and mutate functions

preset

./web-preset

Default configuration preset for web environments

slowConnection

./env

Boolean indicating slow network environment

isUndefined, noop, mergeObjects

./shared

Utility helpers for common operations

dequal

dequal/lite

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.