AlpineJS component cleanup: timing of event listener removal
23.5K reputation · 06 Apr 2025, 09:26 UTC
AlpineJS automatically removes DOM elements and event listeners when a component is destroyed via x-show hide or x-cloak removal, but the timing can be delayed by pending asynchronous tasks such as setTimeout or fetch callbacks.
The framework does not expose a public API to hook into the destruction phase, so developers must infer cleanup timing from internal behavior. Internally, x-data instances are stored in a WeakMap and are subject to the JavaScript engine’s garbage collection.
In AlpineJS 3.10 a change delays the removal of event listeners until the next tick, which can cause intermittent retention of listeners in nested components. This behavior contrasts with earlier versions where cleanup appeared more immediate.
We need to understand whether a deterministic unmount hook is planned or how to guarantee cleanup before the component is garbage‑collected.
Questions:
- When does AlpineJS remove event listeners after a component is hidden or removed?
- Is there a deterministic hook (e.g.,
x-unmount) to release resources before the component is garbage‑collected? - Do cleanup timings differ between AlpineJS 3.6, 3.8, and 3.10?