Optimising API Calls In React

Vaadarsh
2 min readSep 10, 2021

--

Api traffic can slow down your web application modern browser only allow small number of parallel api calls and hence reducing api calls can result in better performance. Often we ignore cancelling apis on unMounting of our component maybe because that make the code more verbose or we are unaware of the case. However not cancelling not only results in blocking some tcp connections it also results in memory leak and updating state of unmounted components. which looks like this

I have developed a custom hook to handle this use case in a super simple and clean way. Here it is

Here is an example how you can use it

now you can do as many get req using the getData method even updating the state and error is handled you just need to pass your setState method just make sure to return cancelRequests function in useEffect that will cancel all api requests made by getData.

you can use async await as well as getData returns a promise and also pass additional object to add headers and other stuff.

Now we have super clean and easy to understand optimised code with less number of lines.

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.

--

--

Vaadarsh
Vaadarsh

Written by Vaadarsh

Senior Software Engineer at Level AI | DTU class of 2021 | Proficient in JavaScript, React.

Responses (5)