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
Middleware(type) anduseSWRare imported from the main SWR entry point.withMiddlewareis imported from an internal module to apply middleware composition to the base SWR hook.
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
immutableis a middleware function adhering to theMiddlewaretype.It wraps the next SWR hook (
useSWRNext) and returns a new SWR hook.Before invoking
useSWRNext, it modifies theconfigobject to disable all automatic revalidation triggers:revalidateOnFocus = false— disables revalidation when window/tab gains focus.revalidateIfStale = false— disables revalidation when the cached data becomes stale.revalidateOnReconnect = false— disables revalidation when the browser reconnects to the network.
This guarantees that once data is fetched, SWR will not attempt to refresh it unless manually triggered.
Parameters
useSWRNext: The next SWR hook in the middleware chain (usually the baseuseSWR).key: The SWR key used to uniquely identify the data.fetcher: The function used to fetch data asynchronously.config: Configuration options for SWR behavior.
Returns
Returns the result of calling
useSWRNextwith the modified configuration.
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
useSWRImmutableis the exported SWR hook enhanced by theimmutablemiddleware.It is created by composing the base
useSWRhook with theimmutablemiddleware viawithMiddleware.This hook can be imported and used in place of the default
useSWRwhen immutable data fetching is desired.
Parameters & Return Value
Same as the base
useSWRhook, but with the guaranteed immutable behavior due to middleware.Accepts
(key, fetcher, config?):key: Unique cache key.fetcher: Function that fetches data.config: Optional SWR configuration (revalidation options overridden internally).
Usage Example
import useSWRImmutable from 'path/to/index'
const { data, error } = useSWRImmutable('/api/user', fetchUser)
Implementation Details and Algorithms
This file uses a middleware pattern that wraps the SWR hook.
The middleware intercepts the hook call and mutates the configuration options to disable automatic revalidation triggers.
Leveraging
withMiddlewareallows clean composition of middleware functions with the base SWR hook, promoting modularity.By overriding
configproperties, this approach avoids duplicating SWR's core fetching logic while changing behavior declaratively.
Interaction with Other System Components
useSWR: The base SWR hook that provides data fetching, caching, and automatic revalidation.withMiddleware: An internal utility to compose SWR middlewares.This file exports a customized SWR hook variant to be used by components or other hooks that require immutable data fetching semantics.
It depends on and extends the core SWR library functionality without modifying its internals.
It fits into the data fetching layer of the application, allowing controlled data freshness policies.
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:
The
immutablemiddleware wraps the baseuseSWRhook (useSWRNext).When invoked, it disables revalidation options in the
config.useSWRImmutableis the resulting hook created by applying theimmutablemiddleware touseSWR.Components use
useSWRImmutableto fetch data with immutable semantics.
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.