Canceling Requests within React Components

Jeong Woo Chang
2 min readMar 3, 2020
Photo by Ricardo Rocha on Unsplash

Why Canceling is Needed? 🔍

When a React component is unmounted, belonging AJAX requests using Fetch/Axios no longer need to be executed. Sometimes, a not canceled request from an unmounted component may trigger some unexpected and unwanted updates.

Fetch

Above code will try to make a request to url and alert the stringified response data after 5 seconds.

It will actually never be able to make the request because controller.abort() is executed before the inner function of the setTimeout runs.

Axios

This code is doing identical task as the above example using Fetch . The only difference is that while Fetch is using AbortController for abort, Axios has its own cancel token, the withdrawn cancelable promises proposal, for canceling.

React Class Component

When you need to implement the canceling logic in React class component, you will need to keep your generated tokens per every requests you made. I assume that the makeRequest is called through an event. When the component is unmounted, you will need to abort all the tokens you made within this component.

React Hooks

Since React v16.8, hooks are available and adopted with high popularity due to its simpleness. This example is the identical implementation of the above class component version.

Conclusion

I introduced the ways to cancel the requests made by Fetch and Axios within a React Component in two differents styles, class and hooks.

By canceling all the belonging requests, there would be no unexpected side effects like trying to updated unmounted React component.

--

--