Efficient Request Handling with React Hooks

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.




Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Secrets of coding style and good commenting

Prettier: Automatically format the code once we save in VS Code

Highly Customizable Tab Component with Vue.js Slots

17 React JS Tools For Developers

Google login with Meteor and Node Js

Centering Google Maps On An App

Reusable Components in React — A Practical Guide

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeong Woo Chang

Jeong Woo Chang

Software Engineer

More from Medium

React State management with Providers

Write a custom Input component with React Hook Form 7+

Fetch, Cache, and Update Data Effortlessly with React Query

Implementing authentication in Remix Applications with Supabase