useRequest.ts
Overview
useRequest.ts is a custom React hook that integrates the HTTP client library Axios with the React data fetching hook SWR to simplify and standardize API requests in React applications. It provides an easy-to-use interface for making HTTP requests, handling loading and error states, caching, and revalidation with minimal boilerplate code.
This hook abstracts the complexity of combining Axios and SWR by:
Accepting an Axios request configuration object.
Using SWR internally to handle caching, revalidation, and state management.
Returning both the raw Axios response and the parsed data.
Supporting fallback data for immediate display before the request resolves.
Exposing useful SWR features like
mutatefor manual cache updates andisValidatingfor loading state.
Detailed Explanation
Types and Interfaces
GetRequest
type GetRequest = AxiosRequestConfig | null
Description: Type alias for the input request configuration accepted by the hook.
Details: Either a valid Axios request configuration object or
nullto disable the request.
Return<Data, Error>
interface Return<Data, Error> extends Pick<
SWRResponse<AxiosResponse<Data>, AxiosError<Error>>,
'isValidating' | 'error' | 'mutate'
> {
data: Data | undefined;
response: AxiosResponse<Data> | undefined;
}
Description: Defines the shape of the object returned by
useRequest.Properties:
data: The parsed response data of typeData, orundefinedif not available.response: Full Axios response object including status, headers, etc., orundefined.error: Axios error object if the request failed.isValidating: Boolean indicating if the request is currently in flight.mutate: Function to manually mutate or revalidate the cached data.
Config<Data, Error>
export interface Config<Data = unknown, Error = unknown> extends Omit<
SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>>,
'fallbackData'
> {
fallbackData?: Data;
}
Description: Configuration options for the hook.
Extends SWR options except it overrides
fallbackDatato accept the raw data instead of the full Axios response.Properties:
fallbackData: Optional initial data of typeDatato be used as the response data before the request completes.
useRequest Hook
function useRequest<Data = unknown, Error = unknown>(
request: GetRequest,
{ fallbackData, ...config }: Config<Data, Error> = {}
): Return<Data, Error>
Purpose: Main exported hook function that performs the HTTP request and manages state.
Parameters:
request: Axios request configuration object ornull. Whennull, the request is disabled.config: Optional configuration extending SWR settings and includingfallbackData.
Returns: An object conforming to the
Returninterface.
Implementation Details
Utilizes
useSWRfrom theswrpackage to handle caching, deduplication, and revalidation.The SWR key is the
requestobject itself. Ifrequestisnull, SWR disables the fetch.The fetcher function calls
axios.requestwith the provided config.The
fallbackDataoption is wrapped into a mock AxiosResponse to match SWR's expected data shape.The hook returns:
data: Simplified Axios response data for ease of use.response: The full Axios response object.error,isValidating,mutate: Exposed from SWR for advanced state management and revalidation.
Usage Example
import useRequest from './useRequest'
interface User {
id: number;
name: string;
}
function UserProfile({ userId }: { userId: number }) {
const { data, error, isValidating, mutate } = useRequest<User>(
{
url: `/api/users/${userId}`,
method: 'GET'
},
{
fallbackData: { id: 0, name: 'Loading...' }
}
);
if (error) return <div>Error loading user.</div>;
if (isValidating) return <div>Loading...</div>;
return (
<div>
<h1>User Profile</h1>
<p>ID: {data?.id}</p>
<p>Name: {data?.name}</p>
<button onClick={() => mutate()}>Refresh</button>
</div>
);
}
Interaction with Other System Components
Axios: Performs the actual HTTP request using the configuration passed to the hook.
SWR: Manages data fetching lifecycle, caching, and revalidation in React.
React Components: This hook is designed to be used inside React functional components to fetch and cache data.
The hook can be integrated into larger data fetching strategies, supporting SSR and client-side hydration through SWR.
Important Implementation Notes
The hook uses the
requestobject as the SWR key, and SWR calls the fetcher only whenrequestis notnull.A TypeScript non-null assertion (
request!) is used to satisfy type checking since SWR internally guards fetcher calls.The
fallbackDatais wrapped into an AxiosResponse shape with default HTTP 200 status to satisfy SWR's internal expectations.The hook abstracts the complexity of handling full Axios responses while exposing them if needed.
Visual Diagram
flowchart TD
A[useRequest Hook]
A -->|accepts| B[GetRequest (AxiosRequestConfig | null)]
A -->|accepts| C[Config (SWRConfiguration + fallbackData)]
A --> D[useSWR]
D -->|key| B
D -->|fetcher| E[axios.request(request)]
E -->|response| D
D -->|returns| F{SWRResponse}
F -->|data| G[AxiosResponse<Data>]
F -->|error| H[AxiosError<Error>]
F -->|isValidating| I[boolean]
F -->|mutate| J[function]
A -->|returns| K[Return<Data, Error>]
K -->|data| L[Data | undefined]
K -->|response| G
K -->|error| H
K -->|isValidating| I
K -->|mutate| J
Summary
useRequest.ts provides a robust, type-safe React hook for data fetching that leverages Axios for HTTP requests and SWR for client-side caching and revalidation. It streamlines API communication in React apps, supporting fallback data, error handling, and advanced cache control, making it a valuable utility for scalable frontend development.