I wrote an article about optimising api calls in react but I recently encountered a scenario where just cancelling the api won’t work because this time the issues were at the server even though you cancel the request it still gets processed by the server. Normally in such scenario we apply debouncing or throttling to prevent extra API calls but the issue is you have to pick a fixed time period for it. It cannot protect your server when it is slow or when your request gets heavy (e.g multiple filter selected at once) and is not able to resolve even after the debounce period (which happened with me). So it can lead to bombardment of your server by a lot of requests even though you have debouncing in place , you may want to increase the debounce period but what about the people who were just making only one request and not multiple, they will suffer.
So to resolve the problem I had an idea of mixing debouncing with maximum number of parallel requests that you want to allow for an action and I created this React hook.
Notice that i’m using refs instead of useState because in setTimeout the state value is not updated correctly (you can read about the issue in detail here ). Also notice that i have placed my debounce function in useCallback and it is not just for the purpose of optimization, you will get more detailed reasons here
Here is an example of how you can use it,
Make sure that you are using the function for the same API call because the debounce period and max parallel requests will apply to all of the functions passed. Maybe you can try to make it accept fetcher logic as an input while instantiating the hook. This will prevent you from using the same function for different calls or you can simply name it differently for each of your use cases.
I will be adding more custom hooks as I encounter new use cases. This is my Github repo if you want to stay connected.
Thanks.