AbortControllers for Components
Not Just For Fetch #
It's somewhat common to see AbortControllers used with fetch, especially since that's why they were first created and that's what the documentation focuses on.
But it's also nice to use them for other things, such as when adding event listeners (i.e. addEventListener()
). Some advantages of using them here are:
- You don't have to keep a reference to the function, in order to later call
removeEventListener()
with that reference. That means inline arrow functions are back on the menu! - You can remove multiple listeners and cancel multiple events, all with a single call.
I find this is especially useful in a component context, where it's good practice to clean up after yourself. For example:
AbortControllers in React Hooks #
function MyComponent() {
useEffect(() => {
const abortController = new AbortController();
window.addEventListener("keydown", () => {}, {
signal: abortController.signal,
});
window.addEventListener("keyup", () => {}, {
signal: abortController.signal,
});
return () => {
abortController.abort("cleanup");
};
}, []);
}
AbortControllers in Custom Elements #
class MyComponent extends HTMLElement {
#abortController = null;
connectedCallback() {
this.#abortController = new AbortController();
window.addEventListener("keydown", () => {}, {
signal: this.#abortController.signal,
});
window.addEventListener("keyup", () => {}, {
signal: this.#abortController.signal,
});
}
disconnectedCallback() {
this.#abortController?.abort("disconnected");
}
}
- Previous: HTMLCollections Are Nice, Actually