global-state.ts
Overview
The global-state.ts file defines and exports a singleton global state container used in the application. Its primary purpose is to maintain a centralized repository of global state related to caching and request deduplication. Specifically, it uses a WeakMap to associate each instance of a cache (Cache) with its corresponding global state (GlobalState).
This global state container plays a crucial role in avoiding redundant or duplicate network requests by sharing state and listeners across different parts of the system that rely on the same cache instance. This helps optimize resource usage and improve performance in scenarios such as data fetching and state management in client-side applications.
Detailed Explanation
Exported Constant: SWRGlobalState
export const SWRGlobalState = new WeakMap<Cache, GlobalState>()
Purpose
SWRGlobalState is a WeakMap that stores the global state associated with each cache instance. It acts as a centralized store to:
Deduplicate requests by ensuring that multiple consumers requesting the same resource share the same ongoing request.
Store listeners or subscribers that react to state changes related to caching.
Types
Key:
Cache— An object representing the caching mechanism or storage.Value:
GlobalState— An object containing the global state details such as ongoing promises, listeners, and possibly metadata related to the cache.
Why WeakMap?
WeakMapallows keys (cache instances) to be garbage collected if there are no other references to them, preventing memory leaks.It ensures the global state does not prevent cache instances from being cleaned up, supporting efficient memory management.
Usage Example
import { SWRGlobalState } from './global-state'
import type { Cache, GlobalState } from '../types'
const cacheInstance: Cache = createCache()
// Initialize global state for this cache if it doesn't exist
if (!SWRGlobalState.has(cacheInstance)) {
SWRGlobalState.set(cacheInstance, {
// Initialize global state properties here, e.g.:
listeners: new Map(),
promises: new Map()
})
}
// Retrieve and use global state
const globalState: GlobalState | undefined = SWRGlobalState.get(cacheInstance)
if (globalState) {
// Use globalState to check or update listeners, promises, etc.
}
Implementation Details
Singleton Pattern: The file exports a single instance of
WeakMapused application-wide, ensuring all parts of the system share the same global state mapping.Memory Efficiency: By leveraging
WeakMap, it avoids retaining caches that are no longer in use, thus preventing memory leaks.Type Safety: Uses TypeScript generics to enforce that keys and values conform to the expected
CacheandGlobalStatetypes.Minimalistic: The file keeps implementation minimal and focused, delegating the structure and management of the actual
GlobalStateto elsewhere in the application.
Interaction with Other Parts of the System
Cache Instances: Each
Cacheinstance created or used in the system is linked with a correspondingGlobalStateobject viaSWRGlobalState.GlobalState Consumers: Components or modules responsible for fetching, caching, and managing data will query and update this global state to coordinate deduplication and listener management.
Type Definitions: The file imports
CacheandGlobalStatetypes from../types, indicating that detailed definitions and possibly the structure of these entities reside in a shared types module.Request Deduplication: This global state map underpins the deduplication logic by tracking ongoing requests, allowing multiple consumers to share the same promise or data fetch.
Listeners Management: It stores listeners or subscribers to cache changes, enabling reactive updates when cached data evolves.
Mermaid Diagram
classDiagram
class SWRGlobalState {
<<WeakMap>>
+Cache: key
+GlobalState: value
+has(cache: Cache): boolean
+get(cache: Cache): GlobalState | undefined
+set(cache: Cache, state: GlobalState): this
+delete(cache: Cache): boolean
}
Explanation:
SWRGlobalStateis represented as aWeakMapwithCacheobjects as keys andGlobalStateobjects as values.The diagram highlights primary methods inherited from
WeakMapused to interact with the global state mapping.
Summary
The global-state.ts file provides a foundational global state container that enables efficient cache-based request deduplication and listener management by associating each cache instance with its global state. It is a lightweight, memory-efficient, and type-safe utility crucial for the caching and data fetching mechanisms throughout the application.
If you need further details about the types Cache and GlobalState, or how the global state is manipulated, please refer to the corresponding type definitions and modules responsible for cache and state management within the project.