React Hooks for fetching, caching and updating asynchronous data
npx @tessl/cli install tessl/npm-ahooksjs--use-request@2.8.0@ahooksjs/use-request is a production-ready React Hook library for managing asynchronous data operations. It provides comprehensive features for data fetching including auto/manual triggering, SWR (stale-while-revalidate) pattern, caching and preloading, refresh on window focus, polling, debounce/throttle, concurrent request handling, pagination, load more functionality, and advanced error handling.
npm install @ahooksjs/use-request or yarn add @ahooksjs/use-requestimport useRequest from "@ahooksjs/use-request";Named imports:
import { useAsync, usePaginated, useLoadMore, UseRequestProvider } from "@ahooksjs/use-request";For CommonJS:
const useRequest = require("@ahooksjs/use-request");
const { useAsync, usePaginated, useLoadMore, UseRequestProvider } = require("@ahooksjs/use-request");import useRequest from "@ahooksjs/use-request";
// Simple GET request
const { data, error, loading } = useRequest('/api/user');
// Manual trigger with parameters
const { data, error, loading, run } = useRequest(
(userId: string) => `/api/user/${userId}`,
{ manual: true }
);
// Execute manually
run('123');
// With options
const { data, error, loading, refresh, mutate } = useRequest('/api/user', {
pollingInterval: 1000, // Poll every second
refreshOnWindowFocus: true, // Refresh when window gains focus
cacheKey: 'user-data', // Enable caching
onSuccess: (data) => console.log('Success:', data),
onError: (error) => console.log('Error:', error),
});@ahooksjs/use-request is built around several key patterns:
useAsync with specialized usePaginated and useLoadMore variationsFundamental async data fetching with comprehensive state management, caching, and lifecycle control.
function useRequest<R = any, P extends any[] = any>(
service: CombineService<R, P>,
options?: BaseOptions<R, P>
): BaseResult<R, P>;
function useRequest<R = any, P extends any[] = any, U = any, UU extends U = any>(
service: CombineService<R, P>,
options: OptionsWithFormat<R, P, U, UU>
): BaseResult<U, P>;Advanced pagination support with table integration, sorting, and filtering capabilities.
function useRequest<R = any, Item = any, U extends Item = any>(
service: CombineService<R, PaginatedParams>,
options: PaginatedOptionsWithFormat<R, Item, U>
): PaginatedResult<Item>;
function useRequest<R = any, Item = any, U extends Item = any>(
service: CombineService<PaginatedFormatReturn<Item>, PaginatedParams>,
options: BasePaginatedOptions<U>
): PaginatedResult<Item>;
type PaginatedParams = [
{
current: number;
pageSize: number;
sorter?: Sorter;
filters?: Filter;
},
...any[]
];Infinite scroll functionality with automatic loading triggers, scroll position recovery, and data accumulation.
function useRequest<R extends LoadMoreFormatReturn, RR>(
service: CombineService<RR, LoadMoreParams<R>>,
options: LoadMoreOptionsWithFormat<R, RR>
): LoadMoreResult<R>;
function useRequest<R extends LoadMoreFormatReturn, RR extends R>(
service: CombineService<R, LoadMoreParams<R>>,
options: LoadMoreOptions<RR>
): LoadMoreResult<R>;
type LoadMoreParams<R> = [R | undefined, ...any[]];
interface LoadMoreFormatReturn {
list: any[];
[key: string]: any;
}Global configuration, context providers, and advanced options for complex application requirements.
const UseRequestProvider: React.ComponentType<{
value: Config;
children: React.ReactNode;
}>;
function useAsync<R, P extends any[]>(
service: Service<R, P>,
options?: BaseOptions<R, P>
): BaseResult<R, P>;
function usePaginated<R, Item, U extends Item = any>(
service: (...p: PaginatedParams) => Promise<R>,
options: PaginatedOptionsWithFormat<R, Item, U>
): PaginatedResult<Item>;
function useLoadMore<R extends LoadMoreFormatReturn, RR>(
service: (...p: LoadMoreParams<R>) => Promise<RR>,
options: LoadMoreOptionsWithFormat<R, RR>
): LoadMoreResult<R>;type Service<R, P extends any[]> = (...args: P) => Promise<R>;
type CombineService<R, P extends any[]> =
| RequestService
| ((...args: P) => RequestService)
| Service<R, P>;
type RequestService = string | RequestServiceObject;
interface RequestServiceObject extends RequestInit {
url?: string;
[key: string]: any;
}
type Mutate<R> = (x: R | undefined | ((data: R) => R)) => void;interface BaseResult<R, P extends any[]> extends FetchResult<R, P> {
reset: () => void;
fetches: {
[key in string]: FetchResult<R, P>;
};
}
interface FetchResult<R, P extends any[]> {
loading: boolean;
data: R | undefined;
error: Error | undefined;
params: P;
cancel: () => void;
refresh: () => Promise<R>;
mutate: Mutate<R>;
run: (...args: P) => Promise<R>;
unmount: () => void;
}
interface PaginatedResult<Item>
extends BaseResult<PaginatedFormatReturn<Item>, PaginatedParams> {
pagination: {
current: number;
pageSize: number;
total: number;
totalPage: number;
onChange: (current: number, pageSize: number) => void;
changeCurrent: (current: number) => void;
changePageSize: (pageSize: number) => void;
[key: string]: any;
};
tableProps: {
dataSource: Item[];
loading: boolean;
onChange: (pagination: PaginationConfig, filters?: Filter, sorter?: Sorter) => void;
pagination: PaginationConfig;
[key: string]: any;
};
sorter?: Sorter;
filters?: Filter;
}
interface LoadMoreResult<R> extends BaseResult<R, LoadMoreParams<R>> {
noMore?: boolean;
loadMore: () => void;
reload: () => void;
loadingMore: boolean;
}interface BaseOptions<R, P extends any[]> {
refreshDeps?: DependencyList;
manual?: boolean;
onSuccess?: (data: R, params: P) => void;
onError?: (e: Error, params: P) => void;
defaultLoading?: boolean;
loadingDelay?: number;
defaultParams?: P;
pollingInterval?: number;
pollingWhenHidden?: boolean;
fetchKey?: (...args: P) => string;
paginated?: false;
loadMore?: false;
refreshOnWindowFocus?: boolean;
focusTimespan?: number;
cacheKey?: CachedKeyType;
cacheTime?: number;
staleTime?: number;
debounceInterval?: number;
throttleInterval?: number;
initialData?: R;
requestMethod?: (service: any) => Promise<any>;
ready?: boolean;
throwOnError?: boolean;
}
interface OptionsWithFormat<R, P extends any[], U, UU extends U> {
formatResult: (res: R) => U;
} & BaseOptions<UU, P>;
interface BasePaginatedOptions<U>
extends Omit<BaseOptions<PaginatedFormatReturn<U>, PaginatedParams>, 'paginated'> {
paginated: true;
defaultPageSize?: number;
}
interface LoadMoreOptions<R extends LoadMoreFormatReturn>
extends Omit<BaseOptions<R, LoadMoreParams<R>>, 'loadMore'> {
loadMore: true;
ref?: RefObject<any>;
isNoMore?: (r: R | undefined) => boolean;
threshold?: number;
}