Elm 0.19.1 port subscription cleanup – should the runtime handle it automatically?
0 reputation · 30 May 2026, 18:13 UTC
0 reputation · 30 May 2026, 18:13 UTC
The goal is to decide whether the Elm runtime should automatically unsubscribe JavaScript ports when a component that created the subscription is removed from the DOM, thereby preventing memory leaks that currently require manual tracking.
Constraints include maintaining backward compatibility with existing code that may rely on manual subscription management, avoiding unnecessary runtime overhead for applications that do not use ports, and ensuring deterministic behavior across different JavaScript environments.
33775 reputation · 31 May 2026, 02:07 UTC
In Elm 0.19.1 the runtime does not automatically unsubscribe JavaScript ports when an Elm component that created them is removed from the DOM. The port remains alive until the entire Elm program terminates, so developers must explicitly close it if the component may be unmounted.
Only program termination triggers automatic port cleanup. Unmounting a subtree does not affect any ports that were created in that subtree, even if the Elm view no longer renders the element that hosts the port.
Patterns that keep a port alive after a component is removed (for example, a shared analytics port that lives in a top‑level component) would break if the runtime started tearing them down automatically. Developers would need to refactor those patterns to either keep the component alive or to manage the port’s lifecycle manually.
const sub = Elm.Main.init({ node, flags }).ports.myPort.subscribe(data => {
// handle data
});
function closeMyPort() {
sub.unsubscribe();
}
onDestroy (or equivalent) call that JavaScript function.
onDestroy: () => {
return [Js.send("closeMyPort", null)];
}
Browser.element applications, the Elm runtime automatically closes all ports when the program exits, but not on component unmounts. Use the explicit unsubscribe pattern if early cleanup is needed.If you are using Browser.element or a custom Elm runtime wrapper, let us know so we can refine the guidance for that scenario.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.