Network request is always one of the core parts of front-end application. The request library has evolved rapidly over the years since jQuery’s encapsulation of Ajax. The request library is finally getting better and faster, especially with hooks. In the traditional request model, the complete flow of a request looks like this:

  • The user clicks, triggering the request process
  • Set the state of related views to Loading
  • The initiating
  • Process the response and disable the loading state of the view

How does the hooks request library make requesting simple for this process?

🌊 Easier request handling

States are simpler: Effect state encapsulation

At the code level, the request library has basically wrapped loading state in hooks. As long as you trigger the request, only care about data and error exposed in hooks and the loading state. Both useRequest and SWR encapsulate this in a general way:

/ / ahooks useRequest
const { data, error, loading } = useRequest(fetcher);

// swr
const { data, error, isValidating } = useSwr('/getList', fetcher);
Copy the code

Caching is even simpler: cacheKey

For one scenario, we go to a sub-page on the home page list and then return. Typically, the page needs to re-initiate the request to get the latest list. If we look at it from a user experience perspective, maybe the data I just saw is not out of date, or I want to go back and see the data I just saw, the experience will be much smoother. If we can store the data cache of the previous page and update the data, then the React diff mechanism will update the page, so that the data can be updated seamlessly. In useRequest, you can set a cacheKey field for a request to read cached data before making a data request if it needs to be pulled again. SWR and react-Query are more radical. The path of the request is the key, and requests made against this key are automatically cached.

const { data, error, loading } = useRequest(getList, {
	cacheKey: 'list'});const { data, error, isValidating } = useSwr('/getList', TodoService);
Copy the code

Cache the Demo

Cache-based page preloading

Because the data is cached based on the request path as the key, we can set up a hidden DOM to request the next page of the current page. When the user enters the next page, the cached data already exists on the next page, which can be opened in seconds. Paging pre-load Demo

Update is simpler: Refetching mechanism

It’s 2021, and Internet speed is no longer a tight resource for most computers. In a traditional scenario, we update data only when the page loads and user action is triggered. With the current request library, update scenarios are already convenient and economical. In SWR, three common scenarios are mainly implemented: focus rerequest, periodic rerequest and reconnected rerequest. Reconnection rerequests are a common scenario for most applications. Focused rerequests are suitable for applications that are sensitive to the immediacy of data, such as the merchant backend. For apps that require high immediacy, such as collaborative office or stock applications, SWR can be used to quickly rerequest.

Editing is easier: mutate mechanism

It is a common scenario to pull server data, edit it, and then update it to the server. The traditional editing logic is to send the result to the server in real time after the user edits, and then pull the edited result from the server. If the network is not good, editors will have a serious sense of lag. In SWR, the idea is to first change local data through mutate, then send local data to the server, and finally pull “validate” results from the server. This allows users to smoothly edit data even in slow network scenarios.

const { data, error, isValidating } = useSwr('/getList', TodoService);
return (
  <div>
    {isValidating && <span className="spin" />}
    {data}
    {error}
    <button
      onClick={()= > {
        mutate('/getList', 'local edit', false);
      }}
    >
      mutate
    </button>
  </div>
)
Copy the code

Mutate Demo (in useRequest, mutate behaves differently from SWR Demo)

Of course, there are many other FEATURES of SWR, you can go to see the documentation, next I will talk about my understanding of these request libraries.

⛰️ The difference between react-query, useRequest, and SWR

In the processing of the above features, the basic three request libraries are implemented. But in the concrete implementation details, the positioning of the three libraries have their own differences.

React-query: finer 🪡

React-query provides the ability to customize almost every feature, sort of the Swiss Army knife of request hooks. For example, SWR and useRequest both simply provide the switch for “rerequest after browser window focus”, while react-Query can do this:

 focusManager.setEventListener(handleFocus= > {
   // Listen to visibillitychange and focus
   if (typeof window! = ='undefined' && window.addEventListener) {
     window.addEventListener('visibilitychange', handleFocus, false)
     window.addEventListener('focus', handleFocus, false)}return () = > {
     // Be sure to unsubscribe if a new handler is set
     window.removeEventListener('visibilitychange', handleFocus)
     window.removeEventListener('focus', handleFocus)
   }
 })

/** in SWR */
const {} = useSWR('/getList', {revalidateOnFocus : false});Copy the code

The details of this hooks are also reflected in the state of the request.

const {
  data,error,isLoading,isError,isSuccess,isIdle,isPaused,status 
} = useMutation('name', getName);
/** simple ~ simple request status ~ */
Copy the code

React-query based customization capabilities are ideal for customizing specific hooks for specific business scenarios.

UseRequest: Closer to Antd🪞

After all, a son.

const { data, loading, pagination } = useRequest(
    ({ current, pageSize }) = > getUserList({ current, pageSize }),
    {
      paginated: true});<Pagination {. pagination} / >
/** * don't say, understand all understand */
Copy the code

SWR: Smoother…

The name Mutate, for example, is interestingly interpreted differently in all three libraries.

  • React-query: useMutation is implemented, which is similar to the manual mode in useRequest.
  • UseRequest: mutate is valid only locally.
  • SWR: After mutate, all related keys are updated. You can also “validate” the data after modifying the local data without initiating the request.

If React-Query is like Android, SWR is like Apple: simple, elegant and smooth. SWR does not think that it is loading data. Instead, after pulling data from the server, IT only “verifies” whether the data is consistent with the server. Given the nature of SWR, I think it is better suited for dealing with Web App scenarios where the front-end experience is heavy.

❓为什么是 Hooks

The above popular request handling libraries are based on hooks. Why can’t the class component do that? This shows the difference between Function Component and Class Component. In Class Component, if you want to reuse logic, you can use mixin mode or HOC mode. The mixin pattern has been abandoned by history; HOC mode can only reuse a piece of logic, it can’t be completely hidden (a simple HOC package request Demo), and it can be confused with Redux Connect and component props. Hooks were originally designed to encapsulate logic that can be reused. So after hooks came along, both the encapsulation of Redux and today’s request processing libraries made a quantum leap in the ability of components to reuse logic.

One More Thing… Modern hooks model

Request libraries now do more with the logic associated with the request. SWR optimizes requests to make front-end applications more independent. When using SWR, the back end can be viewed as a source of data to store data for front-end applications.

www.yuque.com/antchain-fe… 🔥 Ant chain front end hot recruitment 🔥

Resumes can be sent to [email protected].