Efficient Request Handling with React Hooks

Jeong Woo Chang
2 min readJan 4, 2021

--

Photo by Mathew Schwartz on Unsplash

Hooks + Requests 👨‍🔧

There is no single right answer for handling requests with React hooks. After a year of experience with hooks, I have come up with a pretty efficient pattern for that. You can adapt or modify the pattern for your own use.

A Useful Hook 🍭

I like to use Axios for making requests and I will make a useful hooks for handling cancellation tokens for it. You can modify this hooks to use fetch api with AbortController.

Useful hook for Axios

Hooks in the Hook 😵

Photo by Darwin Vegher on Unsplash

I assume that you have a function that use Axios for making a AJAX request and defined as const getItems = () => Promise<string[]> .

Note that original “getItems” is imported as "getItemsAction” and it is wrapped with new function

How is this useful? 🍸

Manually managing requests states across page components are hard to track, code becomes messay and easy to fail. By using the above pattern, these problems are gone.

Whenever a page component that is using getItems for fetching items from useItems hooks is unmounted, unnecessary on-going requests can be canceled seamlessly.

With the cancelAll call at line 10, you can prevent no-more-needed request to be fully executed, when there is a new request.

--

--

No responses yet