index.ts


Overview

This file defines and exports a specialized SWR (stale-while-revalidate) hook variant called useSWRImmutable. It customizes the default SWR behavior by applying an immutable middleware that disables all automatic revalidation triggers, effectively making the fetched data "immutable" during the component lifecycle.

The primary purpose of this file is to provide a convenient, ready-to-use SWR hook variant that guarantees no background revalidation after the initial fetch. This is useful for scenarios where data is known to never change during the session or where you want to explicitly control revalidation.


Detailed Explanation

Imports


immutable Middleware

export const immutable: Middleware = useSWRNext => (key, fetcher, config) => {
  // Always override all revalidate options.
  config.revalidateOnFocus = false
  config.revalidateIfStale = false
  config.revalidateOnReconnect = false
  return useSWRNext(key, fetcher, config)
}

Description

This guarantees that once data is fetched, SWR will not attempt to refresh it unless manually triggered.

Parameters

Returns

Usage Example

import useSWRImmutable from './index'

function MyComponent() {
  const { data, error } = useSWRImmutable('/api/data', fetcher)

  if (error) return <div>Error occurred</div>
  if (!data) return <div>Loading...</div>
  return <div>Data: {JSON.stringify(data)}</div>
}

useSWRImmutable Hook

const useSWRImmutable = withMiddleware(useSWR, immutable)
export default useSWRImmutable

Description

Parameters & Return Value

Usage Example

import useSWRImmutable from 'path/to/index'

const { data, error } = useSWRImmutable('/api/user', fetchUser)

Implementation Details and Algorithms


Interaction with Other System Components


Visual Diagram

flowchart TD
    A[useSWR (base hook)] --> B[immutable Middleware]
    B --> C[useSWRNext(key, fetcher, config)]
    D[useSWRImmutable] --> B
    B -->|Overrides config.revalidate*| C

Explanation:


Summary

This file provides a simple yet effective way to create an immutable data fetching hook based on SWR. By disabling all automatic revalidation triggers through middleware, it ensures data remains stable unless manually refreshed. It cleanly composes with SWR’s existing architecture and is ideal for scenarios where data does not change or should not be revalidated automatically.