Quick Start
The API useRequest
Overview
-
useRequestis a powerful React hook for managing data fetching and state in your applications. It simplifies the process of making API requests, handling loading states, caching, and error management, allowing developers to focus on building features rather than boilerplate code.
Installation
Open inpnpm dlx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRequest.jsonnpx shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRequest.jsonyarn shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRequest.jsonbun shadcn@latest add https://shadcn-ahooks.vercel.app/r/useRequest.jsonUsage
Quick Start
useRequest is a powerful Hooks for asynchronous data management. useRequest is sufficient enough for network request scenarios in React projects.
useRequest organizes code through a plug-in pattern, the core code is extremely simple, and can be easily extended for more advanced features. Current features include:
- Automatic/manual request
- Polling
- Debounce
- Throttle
- Refresh on window focus
- Error retry
- Loading delay
- SWR(stale-while-revalidate)
- Caching
Next, let's get to know useRequest from the two simplest examples.
Default usage
The first parameter of useRequest is an asynchronous function, which will be automatically triggered when the component is first loaded. At the same time, it automatically manages the status of loading, data, error of the asynchronous function.
const { data, error, loading } = useRequest(getUsername);
Manual trigger
If options.manual = true is set, useRequest will not be executed by default, and the execution needs to be triggered by run.
const { loading, run } = useRequest(changeUsername, {
manual: true
});
In the above two examples, we demonstrated the most basic usages of useRequest. Next, we will introduce the features of useRequest one by one.