Canceling Requests within React Components

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.

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Build Your Own CRA Template

LeetCode 100 Same Tree

Boost Performance with Web Workers: A Detailed Guide

Why You Should Run Automated Web App Testing

LeetCode 198_House Robber

How to Build a To-Do List With React

What I Learned/Noticed Turning Semantic Cards into Links

Where does Redux fit in Meteor?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jeong Woo Chang

Jeong Woo Chang

Software Engineer

More from Medium

React.memo with useCallback to avoid optimising the rendering in React

Getting Started with Rich Text Editors in React

Virtual DOM and diffing- algorithm

Write a simplified version of React to fully understand the fiber architecture