How Modern Hook-Based Request Libraries Simplify Frontend Data Fetching
Modern hook-based request libraries such as useRequest, SWR, and react-query transform traditional request flows by encapsulating loading states, caching, refetching, and mutation handling, offering simpler APIs, better user experience, and seamless integration with React’s component model.
Network requests are a core part of frontend applications. From jQuery's ajax wrapper to axios, request libraries have rapidly evolved, and with the advent of hooks they have entered a new era.
In the traditional request model, a complete request flow looks like:
User clicks, triggering the request process
Set related view state to loading
Initiate the request
Handle the response and turn off the loading state
What new mechanisms do hook‑based request libraries use to simplify the process and improve user experience?
Simpler request handling
Modern request libraries encapsulate the loading state inside hooks, exposing only
data,
errorand a loading flag.
<code>const { data, error, loading } = useRequest(fetcher);</code>
<code>const { data, error, isValidating } = useSwr('/getList', fetcher);</code>Simpler cache: cacheKey mechanism
When a user navigates back to a previously visited page, caching the previous data avoids a full reload, especially on weak networks. useRequest allows a
cacheKeyto read cached data before refetching, while SWR and react‑query automatically cache based on the request path.
<code>const { data, error, loading } = useRequest(getList, {</code>
<code> cacheKey: 'list',</code>
<code>});</code>
<code>const { data, error, isValidating } = useSwr('/getList' /* path is cacheKey */, TodoService);</code>Cache‑based pagination preloading
By using the request path as a key, a hidden DOM can request the next page in advance, enabling instant page switches.
Demo: swr cache demo
Simpler update: Refetching mechanism
In 2021, network speed is generally sufficient, so updates can be triggered by focus, interval, or reconnection. SWR supports focus‑revalidation, interval revalidation, and reconnection revalidation, catering to both data‑sensitive dashboards and real‑time apps.
Simpler edit: mutate mechanism
Instead of sending edits directly to the server, SWR’s
mutateupdates local data first, then syncs with the server, providing a smooth editing experience even on slow networks.
<code>const { data, error, isValidating } = useSwr('/getList', TodoService);</code>
<code>return (</code>
<code> <div></code>
<code> {isValidating && <span className="spin" />}</code>
<code> {data}</code>
<code> {error}</code>
<code> <button onClick={() => { mutate('/getList', 'local edit', false); }}>mutate</button></code>
<code> </div></code>
<code>);</code>Demo: swr mutate demo
react‑query, useRequest and swr differences
All three libraries implement the same features, but their design philosophies differ.
react‑query: more granular
Provides fine‑grained customization for each feature, such as focus‑based refetching via a focus manager.
<code>focusManager.setEventListener(handleFocus => {</code>
<code> if (typeof window !== 'undefined' && window.addEventListener) {</code>
<code> window.addEventListener('visibilitychange', handleFocus, false);</code>
<code> window.addEventListener('focus', handleFocus, false);</code>
<code> }</code>
<code> return () => {</code>
<code> window.removeEventListener('visibilitychange', handleFocus);</code>
<code> window.removeEventListener('focus', handleFocus);</code>
<code> };</code>
<code>});</code>
<code>// SWR equivalent</code>
<code>const {} = useSwr('/getList', { revalidateOnFocus: false });</code>react‑query also exposes a rich set of status flags (isLoading, isError, isSuccess, etc.) for precise control.
useRequest: closer to Ant Design
Developed by the Umi team, useRequest integrates smoothly with Ant Design and offers a manual trigger option for better control.
<code>const { data, loading, pagination } = useRequest(</code>
<code> ({ current, pageSize }) => getUserList({ current, pageSize }),</code>
<code> { paginated: true }</code>
<code>);</code>
<code><Pagination {...pagination} /></code>swr: smoother experience
swr’s
mutateupdates all keys associated with the request, optionally delaying the server call, and provides a global mutate function for lightweight scenarios.
react‑query: implements useMutation, similar to useRequest’s manual mode.
useRequest: mutate only affects local data.
swr: mutate triggers all related keys, can update locally then verify with server.
Why hooks?
Class components rely on mixins or HOCs for logic reuse, which are limited or cumbersome. Hooks were designed for reusable logic, enabling request libraries and other abstractions to provide clean, composable APIs.
One More Thing… Modern hooks model
After the front‑back separation wave, frontend development has accelerated. While tooling is mature, user experience remains the next frontier, especially on mobile networks where instability affects Web Apps. Hook‑based request libraries enable caching, silent requests, and reduced full‑page refreshes, making Web Apps more independent and responsive.
By optimizing requests with hooks, frontend apps become more autonomous, leveraging cacheKey, refetching, and other mechanisms to hide network latency and deliver a seamless user experience.
So, as a passionate frontend developer, what are you waiting for? Start using hooks now!
Taobao Frontend Technology
The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.