useUnmountSignal() — A React Hook to cancel promises when a component is unmounted

A React Hook that wraps around the almighty AbortController. It will automatically call abort() on the created AbortSignal instance when the component unmounts. import useUnmountSignal from 'use-unmount-signal'; function Example() { const unmountSignal = useUnmountSignal(); return ( <button onClick={() => fetch('https://ping.example.com', { signal: unmountSignal }) }> Ping </button> ); } Installation per NPM: npm i use-unmount-signal …

How to Clean up Async Effects in React

Dmitri Pavlutin walks us through properly cleaning up side-effects in React: From time to time you might have difficulties at the intersection of component lifecycle (initial render, mount, update, unmount) and the side-effect lifecycle (start, in progress, complete). Tackled are fetch requests, timers like setTimeout(), debounce or throttle functions, etc. With the techniques applied, you …

Cancel JavaScript Event Listeners with AbortController

One of the new features that was added in Chrome 88 is the ability to pass an AbortController‘s signal into addEventListener. const controller = new AbortController(); const { signal } = controller; document.querySelector(‘…’).addEventListener(‘foo’, (e) => { // … }, {signal}); By calling controller.abort();, you can remove the listener from the event target, just like when …

Cancel a JavaScript Promise with AbortController

👋 This post also got published on Medium. If you like it, please give it some love a clap over there. In How to Cancel Your Promise Seva Zaikov has done a nice writeup exploring several attempts on how to cancel promises. After also touching generators and async/await the conclusion is that you can’t actually …