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 🍭
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> .
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.
cancelAll call at line 10, you can prevent no-more-needed request to be fully executed, when there is a new request.