index.ts
Overview
The index.ts file serves as the primary entry point and export aggregator for the SWR (stale-while-revalidate) library’s core functionalities and types. It re-exports the main hooks, configuration components, utility functions, and TypeScript types that constitute the public API of the SWR package.
SWR is a React Hooks library for data fetching that provides convenience, efficiency, and flexibility by leveraging caching, revalidation, focus tracking, and other strategies. This file consolidates exports from internal modules and exposes them to the consumers of the library, enabling easy import and usage.
Exported Entities
Default Export
useSWR
Source:
./use-swrDescription: The primary React hook to fetch data with caching and revalidation capabilities.
Usage Example:
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
return <div>Hello {data.name}!</div>
}
Remarks: This hook encapsulates the core SWR algorithm and provides a simple interface to fetch and cache data in React components.
Named Exports
SWRConfig
Source:
./use-swrDescription: A React context provider component that allows setting global configuration options for all SWR hooks in the application.
Usage Example:
import { SWRConfig } from 'swr'
function App() {
return (
<SWRConfig value={{ refreshInterval: 3000 }}>
<Profile />
</SWRConfig>
)
}
Remarks: Provides a way to globally customize SWR behavior such as refresh intervals, error retries, fetcher functions, etc.
unstable_serialize
Source:
./serializeDescription: A utility function to serialize keys used in SWR caching.
Usage: Typically used internally or for advanced cache key manipulation.
Remarks: Marked as unstable, indicating potential API changes.
useSWRConfig
Source:
../_internalDescription: A React hook to access the current SWR global configuration context.
Usage Example:
import { useSWRConfig } from 'swr'
function Component() {
const { cache, mutate } = useSWRConfig()
// use cache or mutate directly
}
mutate
Source:
../_internalDescription: A function to mutate the cached data manually, causing revalidation or updating cache directly.
Usage Example:
import { mutate } from 'swr'
async function updateUser() {
await fetch('/api/update-user', { method: 'POST' })
mutate('/api/user') // revalidate the user data
}
preload
Source:
../_internalDescription: Function to preload data into the cache without rendering a component.
Usage: Useful for prefetching data for faster subsequent use.
TypeScript Interfaces and Types
SWRGlobalConfig
Description: Interface representing the global configuration options for SWR.
Current Content: Empty interface (placeholder for future options such as
suspense).Example:
export interface SWRGlobalConfig {
// suspense: true
}
Exported Types from ../_internal
Types Included:
SWRConfigurationRevalidatorRevalidatorOptionsKeyKeyLoaderKeyedMutatorSWRHookSWRResponseCacheBareFetcherFetcherMutatorCallbackMutatorOptionsMiddlewareArgumentsStateScopedMutator
Purpose: These types define the shapes and contracts for the hooks, cache keys, fetchers, mutation callbacks, middleware, and internal states used throughout SWR.
Implementation Details and Algorithms
This file itself contains minimal logic or algorithms, serving primarily as an export hub. The real implementations reside in the imported modules:
./use-swr: Implements the mainuseSWRhook andSWRConfigprovider../serialize: Contains serialization logic for cache keys.../_internal: Contains internal hooks, utilities, mutation logic, and type definitions.
The SWR hook uses the stale-while-revalidate caching strategy, where cached data is returned immediately (stale), then revalidated asynchronously in the background to update with fresh data.
Interaction with Other System Components
This file acts as the interface boundary of the SWR package.
It aggregates exports from internal modules (
use-swr,serialize, and_internalfolder) and re-exports them for public consumption.Other parts of the system, such as UI components or higher-level modules, import from this file to use SWR’s data fetching capabilities.
The
SWRConfigprovider enables global configuration affecting alluseSWRhooks within the React component tree.The mutation and preload utilities allow imperative cache manipulation outside React hooks, supporting advanced use cases.
Visual Diagram
flowchart TD
A[useSWR]
B[SWRConfig]
C[unstable_serialize]
D[useSWRConfig]
E[mutate]
F[preload]
G[Types from ../_internal]
subgraph "index.ts exports"
A
B
C
D
E
F
G
end
A --> B
B --> D
D --> E
E --> F
G -.-> A
G -.-> B
Summary
The index.ts file is a centralized export module that exposes SWR’s key APIs, configuration utilities, and types. It provides the public interface for the library, enabling seamless integration of SWR’s powerful data fetching and caching features into React applications, while hiding internal implementation details. This modular export strategy supports maintainability and scalability of the SWR codebase.