Track 02 · Lesson 6 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
Listener options and cleanup
Lesson 6 of 17· 7 min
addEventListener takes options that change how a listener behaves, and every listener you add should eventually be removed, or it keeps running, and holding memory, after you no longer need it.
Subscribe, unsubscribe
Three options, three panels
once and removeEventListener
0 times the handler ran. Listener attached.
AbortController: remove many at once
0 listeners active. Pointer moves: 0, clicks: 0.
passive: let scrolling start immediately
The listener below calls preventDefault() on every wheel and touch-move event. Scroll inside the box with each setting.
Scroll me with a mouse wheel, trackpad or finger.
You scrolled down here.
The end.
Non-passive listener attached. Try scrolling the box.
button.addEventListener("click", claim, { once: true });
button.removeEventListener("click", claim); // needs the same function
const controller = new AbortController();
pad.addEventListener("pointermove", onMove, { signal: controller.signal });
pad.addEventListener("click", onClick, { signal: controller.signal });
controller.abort(); // removes both
window.addEventListener("scroll", onScroll, { passive: true });
// React: clean up in useEffect
useEffect(() => {
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
return () => controller.abort();
}, []);Removing a listener#
removeEventListener needs the same function you added. Passing a fresh arrow function that looks identical does nothing, because it's a different function. That's why the demo keeps one stable handler.
An AbortController avoids that bookkeeping. Pass its signal to as many listeners as you like, then call abort() once to remove them all. The same signal also cancels fetch requests, so one cleanup can stop everything a component started.
passive: true#
The browser can't start scrolling until it knows whether your wheel or touch listener will call preventDefault(). A passive listener promises it won't, so scrolling starts immediately. Unless you truly need to cancel scrolling, mark scroll, wheel and touch listeners passive.
Check yourself