Efficient Request Handling with React Hooks
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.
Hooks in the Hook 😵
I assume that you have a function that use Axios for making a AJAX request and defined as const getItems = () => Promise<string[]>
.
getItems”
is imported as "getItemsAction”
and it is wrapped with new functionHow 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.