Libraries optimize API calls

A large number of API calls can slow down your web application, and today’s browsers only allow a small number of parallel API calls, so reducing API calls can lead to better performance. Often we omit to cancel API calls when removing components, either because it makes the code more verbose or because we are unaware of the situation. However, not cancelling can not only cause some TCP connections to be blocked, but can also cause memory leaks and update the state of removed components. Something like this:

I developed a custom hook to handle this use case in a very simple and clean way. The hooks are as follows:

Here’s an example of how to use it:

Now you can use getData to do as many API requests as you want, even update status and error handling, just pass your setState method, make sure to return cancelRequests in useEffect, It cancels all API requests made by getData.

You can use async await and getData to return a promise and pass additional objects to add titles and other content.

Now we have very clean and easy to understand optimized code with fewer lines.

I’ll add more custom hooks as I come across new use cases, and here’s my Github repository if you want to keep in touch.

thank you