Cancel Axios request on component unmount | React.js (Hooks)

Santosh Subedi
2 min readApr 24, 2021

I am not gonna bore you with a detailed explanation so Let’s start with a question.

Q. what are we doing here?

Let us consider a scenario, you have a Products component which displays all the product by fetching data from the server but this fetch takes 5 sec to respond. Okay, so what happens when the user changes the route from /api/products to /api/foo before 5 seconds is completed ?.
The answer is that the app will still continue to get products from the server even though it is on a completely different route/path which leads to an unoptimized API call.

Here I wanna make the explanation simple. So what mount and unmount means?
Mount: Show
Unmount: Hide

App.js
App.js
Products.js

`setProducts` only when <Product /> component is visible/mounted.
Otherwise, we will get

Now let’s see how our app functions

So now in order to stop products fetch, we are going to cancel the axios request by using axios cancel token as below.

Products.js

Now let’s see how our app functions after modification

If I missed here something, made a mistake or you have any questions do let me know.

--

--