Skip to content
Latestv1.0.63

useRequestSWR

useRequestSWR is a Vue Hook designed specifically to implement the Stale-While-Revalidate caching strategy. It prioritizes displaying cached (stale) data during the initial screen load or dependency updates, while silently executing a network request in the background (revalidate) to fetch the latest data and update, providing a latency-free user experience.

Basic Usage & SWR Cache Strategy Demo

In the interactive demo below:

  • Selecting a user for the first time triggers a 1-second load request.
  • Switching back to a user that has already been loaded displays their cached details instantly (zero delay). Simultaneously, a silent revalidation request is executed in the background.
  • After 1 second, the background fetch completes and updates the view seamlessly. The tag status returns to "Data Cached" and the refreshed timestamp updates.
  • This demo sets staleTime: 5000. If you reselect a user within 5 seconds, it is considered fresh and no revalidation is triggered.
SWR Cache Loading Demo

Options

typescript
export interface UseRequestSWROptions<TData, TParams extends unknown[]> extends UseRequestOptions<
  TData,
  TParams
> {
  swr?: boolean // Enable SWR mode
  cacheKey?: string // Cache key
  staleTime?: number // Stale threshold (ms)
  cacheTime?: number // Retention threshold (ms)
  getCache?: (key: string) => TData | undefined // Custom cache reader
  setCache?: (key: string, value: TData) => void // Custom cache writer
  refreshOnWindowFocus?: boolean // Revalidate when window focuses
  refreshDepsWait?: number // Debounce for dependency changes
  refreshDeps?: Ref<unknown>[] // Dependency array
}

Recommendation

  • List / Config interfaces: set staleTime to 5-30 minutes.
  • Detail interfaces: set staleTime to 1-5 minutes.
  • Real-time interfaces (e.g., Stocks, Monitors): SWR is not recommended (or staleTime = 0).

Custom Cache Management

You can supply custom getCache / setCache to integrate with external state managers (e.g., Pinia or IndexedDB).

typescript
import { reactive } from 'vue'

const cacheStore = reactive(new Map<string, unknown>())

const { data } = useRequestSWR('app_config', (key) => request.get('/api/config'), {
  getCache: (key) => cacheStore.get(key),
  setCache: (key, value) => cacheStore.set(key, value)
})

Coordination with Pagination / Load More

For typical list navigation, we recommend using dedicated hooks:

SWR is most useful as a caching strategy for detail views or global configuration datasets.

Summary

  • useRequestSWR displays stale cached data immediately for subsequent views, revalidating against the backend silently.
  • Ideal for read-heavy, write-light endpoints that do not require absolute real-time currency on every page load.
  • Operates on reactive dependencies and independent lifecycles.

Released under the MIT License.