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

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>
}

Named Exports

SWRConfig

import { SWRConfig } from 'swr'

function App() {
  return (
    <SWRConfig value={{ refreshInterval: 3000 }}>
      <Profile />
    </SWRConfig>
  )
}

unstable_serialize


useSWRConfig

import { useSWRConfig } from 'swr'

function Component() {
  const { cache, mutate } = useSWRConfig()
  // use cache or mutate directly
}

mutate

import { mutate } from 'swr'

async function updateUser() {
  await fetch('/api/update-user', { method: 'POST' })
  mutate('/api/user') // revalidate the user data
}

preload


TypeScript Interfaces and Types

SWRGlobalConfig

export interface SWRGlobalConfig {
  // suspense: true
}

Exported Types from ../_internal


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:

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


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.