Skip to main content
A Frehner Site

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:

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");
	}
}