useRequest.js
Overview
useRequest.js defines a custom React Hook useRequest that simplifies data fetching and caching by combining axios for HTTP requests with useSWR for state management and caching. This hook provides a declarative and efficient way to perform API calls, handle loading states, manage cached data, and support fallback data for initial render.
The primary functionality of this file is to wrap an HTTP request configuration or URL string into a reusable hook that leverages SWR's smart caching and revalidation strategies, while internally using axios to perform the actual network request.
Detailed Explanation
useRequest Hook
export default function useRequest(request, { fallbackData, ...config } = {}) { ... }
Purpose
useRequest is a custom React Hook designed for fetching data using axios and caching it using useSWR. It allows passing an axios request configuration (or a URL string) and optional SWR configuration including fallback data to initialize state before the actual request completes.
Parameters
request(string | Object):
The HTTP request to be made, either as a URL string or an axios request config object.
Examples:'https://api.example.com/data'(simple GET request URL){ url: '/api/items', method: 'POST', data: { id: 1 } }(custom axios config)
options(Object, optional): Configuration object with the following properties:fallbackData(any): Initial data to use as fallback before the request completes. This data is wrapped into a mock axios response object withstatus: 200andstatusText: 'InitialData'....config(Object): Additional configuration options passed touseSWR, such asrevalidateOnFocus,refreshInterval, oronError.
Return Value
The hook returns the result of useSWR with the configured fetcher. The typical return object includes:
data: The response data from the request (orfallbackDataif provided and still loading).error: Error object if the request failed.isLoading: Boolean indicating if the request is in progress.mutate: Function to manually update or revalidate the cached data.
Usage Example
import useRequest from './useRequest'
function UserProfile({ userId }) {
const { data, error, isLoading } = useRequest(`/api/users/${userId}`, {
fallbackData: { name: 'Loading...', age: null },
revalidateOnFocus: false,
})
if (isLoading) return <p>Loading user profile...</p>
if (error) return <p>Error loading user profile.</p>
return (
<div>
<h1>{data.name}</h1>
<p>Age: {data.age}</p>
</div>
)
}
Implementation Details
The hook uses
useSWRfor caching, revalidation, and state management of remote data fetching.The fetcher function passed to
useSWRusesaxiosto perform the HTTP request.The
requestparameter is directly passed toaxios. If it is undefined or falsy, an empty object{}is passed to avoid errors.If
fallbackDatais provided, it is wrapped in an object mimicking an axios response structure (status,statusText,headers, anddata) and passed asfallbackDatatouseSWR. This allows immediate rendering of initial data in the SWR cache.Additional SWR config options can be passed and override the defaults.
Interaction with Other Parts of the System
axios: The hook relies on axios to perform HTTP requests. The axios instance can be customized elsewhere (e.g., interceptors, base URL).useSWR: This hook depends on SWR for caching, deduplication, and automatic revalidation. It integrates axios calls into SWR’s data-fetching lifecycle.React components: Components import and call
useRequestto fetch and display remote data easily, benefiting from caching and real-time updates.Potential Extensions: This hook can be enhanced to include error transformation, request cancellation, or integration with authentication tokens.
Mermaid Diagram
flowchart TD
A[useRequest Hook] -->|calls| B[useSWR Hook]
B -->|fetcher function| C[axios(request)]
C -->|returns| D[Promise of axios response]
B -->|returns| E[Data, error, isLoading, mutate]
A -->|returns| E
subgraph Parameters
F[request]
G[options: fallbackData, config]
end
F --> A
G --> A
E -->|used by| H[React Component]
Summary
useRequest.js provides a clean, reusable custom hook for making HTTP requests with axios wrapped in SWR's caching and state management. It abstracts away boilerplate and promotes efficient data fetching patterns in React applications, supporting fallback data and customizable revalidation behavior. This file plays a critical role in the data access layer of the application by bridging HTTP requests and React's UI rendering with state synchronization.