config-context.ts
Overview
The config-context.ts file implements a React context provider component (SWRConfig) that manages configuration settings for the SWR (stale-while-revalidate) data fetching library. It enables scoped or global configuration management through React’s context API, allowing SWR hooks in the component tree to consume unified or layered configuration options seamlessly.
This file handles:
Creation of the
SWRConfigContextReact context for sharing configuration.The
SWRConfigcomponent that merges parent and local configurations.Initialization of a custom cache provider if specified.
Lifecycle management to clean up cache subscriptions.
Propagation of the composed configuration (including cache and mutation functions) down to SWR hooks consuming the context.
By centralizing configuration in this manner, the file allows flexible, composable, and dynamic configuration of SWR hooks in React applications, supporting advanced features like custom cache providers and middleware enhancements.
Detailed Explanations
SWRConfigContext
export const SWRConfigContext = createContext<Partial<FullConfiguration>>({})
Type:
React.Context<Partial<FullConfiguration>>Purpose: Provides a React context to hold partial or full SWR configuration objects.
Usage: Used internally by
SWRConfigto supply configurations and by SWR hooks to consume them.
SWRConfig Component
const SWRConfig: FC<
PropsWithChildren<{
value?:
| SWRConfiguration
| ((parentConfig?: SWRConfiguration) => SWRConfiguration)
}>
> = props => { ... }
Type: React Functional Component
Props:
value(optional): Eithera plain
SWRConfigurationobject, ora function accepting the current parent config and returning a new
SWRConfiguration.
children: React children components that will receive this configuration context.
Returns: JSX element providing
SWRConfigContext.Providerwith merged configuration.
Parameters
Parameter | Type | Description |
|---|---|---|
| `SWRConfiguration \ | (parentConfig?: SWRConfiguration) => SWRConfiguration` |
|
| Child components wrapped by this provider. |
Functionality & Workflow
Consume Parent Configuration:
Uses
useContext(SWRConfigContext)to obtain the nearest parent configuration.Resolve Current Configuration:
Checks if
valueprop is a function (isFunction(value)).If a function, calls it with
parentConfigto get current config.Otherwise, uses the
valuedirectly.
Merge Configurations:
If
valueis a function, the returned config replaces or extends the parent config.If
valueis an object, merges it withparentConfigusingmergeConfigs.
Cache Provider Initialization:
Checks if the
providerproperty is set in the current config.If yes, initializes a cache context using
initCachewith the provided cache and config.Uses
useRefto ensure cache initialization happens only once.
Cache and Mutate Override:
If a cache context exists, overrides
cacheandmutatein the extended config with values from the cache context.
Lifecycle Cleanup:
Uses
useIsomorphicLayoutEffectto unsubscribe from cache events on unmount to avoid memory leaks.
Provide Context:
Returns a
SWRConfigContext.Providerelement that wrapsprops.children.Passes the fully merged and extended config as the context value.
Return Value
JSX.Element: A
SWRConfigContext.Providercomponent that supplies the merged configuration to child components.
Usage Example
import SWRConfig from './config-context'
function App() {
const globalConfig = {
refreshInterval: 3000,
fetcher: (url: string) => fetch(url).then(res => res.json()),
}
return (
<SWRConfig value={globalConfig}>
<MyComponent />
</SWRConfig>
)
}
In this example, MyComponent and all its descendants will consume the globalConfig via the SWR context.
Important Implementation Details
Functional vs Object Configuration:
The component supports
valueas either an object or a function returning an object. This enables dynamic, context-aware configuration merging.Cache Provider Handling:
The
providerproperty in the configuration allows injecting a custom cache mechanism. The cache is initialized once and injected into the configuration to ensure scoped cache and mutation control.initCacheIntegration:The
initCachefunction (imported from './cache') returns a tuple that includes the cache instance, mutate function, and unsubscribe handlers. These are used to manage cache lifecycle and event subscriptions.Use of
useIsomorphicLayoutEffect:This hook ensures cleanup logic runs correctly on both server and client environments to prevent memory leaks and stale subscriptions.
Merging Strategy:
The merging of configurations is done via
mergeConfigsandmergeObjectsutilities which perform deep merges, preserving nested config keys like middleware chains.Context Propagation:
By using React’s context API, the configuration seamlessly flows down the component tree, making it accessible without prop drilling.
Interaction with Other Parts of the System
./config: Provides the default cache instance used if no custom provider is specified../cache: ContainsinitCache, which initializes and manages cache instances and mutation logic../merge-config: Contains themergeConfigsutility to deeply merge two configuration objects../shared: Provides utilities likeisFunction,mergeObjects, and constants likeUNDEFINED../env: SuppliesuseIsomorphicLayoutEffecthook for environment-safe side effects.SWR Hooks:
The configurations provided here are consumed by core SWR hooks (
useSWR) to control behavior such as caching, revalidation, middleware application, data fetching, and mutation.Middleware Architecture:
This context provider enables middleware stacking by merging middleware arrays within the config, allowing enhanced behaviors in SWR hooks (e.g., devtools, preloading).
Mermaid Diagram
classDiagram
class SWRConfigContext {
<<React Context>>
+Partial<FullConfiguration> value
}
class SWRConfig {
+value?: SWRConfiguration | (parentConfig?: SWRConfiguration) => SWRConfiguration
+children: ReactNode
-parentConfig: Partial<FullConfiguration>
-config: SWRConfiguration
-extendedConfig: SWRConfiguration
-cacheContextRef: React.RefObject
+render(): JSX.Element
}
SWRConfig --> SWRConfigContext : provides
SWRConfig o-- "1" initCache : initializes cache via
SWRConfig --> useContext : reads parentConfig
SWRConfig --> useMemo : memoizes merged configs
SWRConfig --> useIsomorphicLayoutEffect : manages lifecycle cleanup
Summary
The config-context.ts file is a pivotal part of the SWR library’s configuration management system. It defines a context provider component that allows React applications to specify and inherit SWR configurations in a composable and dynamic way. It supports merging configurations, injecting custom cache providers, managing lifecycle cleanup, and enabling middleware composition. This design enables robust, flexible, and scalable data fetching configurations across complex React component trees.