use-remote-data.ts
Overview
The use-remote-data.ts file provides a minimalistic React hook implementation for fetching remote data using the SWR (stale-while-revalidate) data fetching library. It exports two main utilities:
useRemoteData: A React hook that abstracts fetching data from a remote API endpoint (/api), handling loading states and errors using SWR’s suspense mode.preloadRemote: A function to preload the remote data in advance, improving perceived performance by initiating the fetch before the hook is rendered.
The file demonstrates a simple retry logic where the first fetch attempt always fails, forcing SWR to retry fetching the data.
Detailed Explanation
Imports
useSWRandpreloadare imported from the swr package.useSWRis the core hook used to fetch, cache, and update remote data reactively.preloadallows fetching and caching data without rendering, supporting data preloading.
Variables and Constants
count: number
A module-scoped counter tracking how many times the fetcher function has been called.
fetcher: () => Promise
An asynchronous function responsible for fetching data from the remote API.
On the first call (
count === 1), it intentionally rejects with an error'wrong'. This simulates a failure scenario to test retry behavior.On subsequent calls, it fetches JSON data from the
/apiendpoint and returns thedatafield from the JSON response.
Usage:
fetcher().then(data => console.log(data)).catch(err => console.error(err))
Constants
key: string
A static key string 'manual-retry' used by SWR to uniquely identify the cached data associated with this fetch.
Exported Functions
useRemoteData(): any
A React hook that calls useSWR with the static key and fetcher function.
It enables suspense mode (
suspense: true), meaning it throws a Promise while loading, allowing React Suspense boundaries to handle loading states.When data is successfully fetched, it returns that data.
If fetching fails (like on the first call), SWR retries automatically because the fetcher rejects once and then succeeds.
Parameters: None
Returns: The data fetched from the remote API (r.data from the fetcher).
Example usage:
import { useRemoteData } from './use-remote-data'
function MyComponent() {
const data = useRemoteData() // Suspense boundary required
return <div>{JSON.stringify(data)}</div>
}
preloadRemote(): void
This function preloads the data associated with the same key by calling preload(key, fetcher).
Useful to invoke before rendering components that use
useRemoteDatato reduce wait time.Does not return anything; it triggers the fetch and caches the result in SWR’s internal cache.
Example usage:
import { preloadRemote } from './use-remote-data'
preloadRemote() // Initiate data fetch early
Implementation Details and Algorithms
Retry Logic: The
fetcherfunction is designed to fail on the first call deliberately, enabling SWR’s automatic retry mechanism to kick in. This is a minimal demonstration of error handling and retry support.Suspense Mode: By enabling suspense, the hook integrates with React Suspense, allowing declarative loading states and improved UX.
Static Keying: Using a constant
keyensures that the same cached resource is shared across all hook usages and preloads, preventing duplicated requests.
Interaction with Other Parts of the Application
This file is likely part of a data fetching layer in the application.
Components that need remote data from
/apiimport and useuseRemoteDatafor reactive data access.preloadRemotecan be called from higher-level components or routing logic to warm up the cache before components mount.The SWR cache acts as a shared data store, enabling consistent and performant data sharing across components.
The
/apiendpoint is expected to be present and return JSON data with adatafield.
Visual Diagram
flowchart TD
A[useRemoteData Hook] -->|calls| B[useSWR(key, fetcher, suspense:true)]
B -->|uses| C[fetcher function]
D[preloadRemote Function] -->|calls| E[preload(key, fetcher)]
C -->|fetches| F[/api Endpoint]
B -->|returns| G[data or throws Promise]
useRemoteDatainternally callsuseSWRwith thefetcherandkey.fetcherhandles fetching and retry logic.preloadRemotecallspreloadwith the same key and fetcher to trigger early caching.Both
useRemoteDataandpreloadRemoterely on the samekeyandfetcherto share cached data.The fetcher interacts with the
/apiendpoint to retrieve data.
Summary
This file encapsulates a simple yet effective pattern for remote data fetching with SWR in React, featuring:
A retry-enabled fetcher function with controlled failure on the first attempt.
A suspense-enabled React hook for declarative data consumption.
A preload function to warm the cache for better UX.
Clear separation of concerns and consistent cache keying.
It is a lightweight utility designed to be integrated into React components that require remote asynchronous data loading with automatic retries and suspense support.