Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call ResizeObserver.unobserve for removed elements?

When some observed element gets removed from DOM, should I call .unobserve for that element to prevent memory leaks, or will it be "unobserved automatically"?

const ro = new ResizeObserver((entries) => { console.log(entries); });
const el = document.getElementById('foo');
ro.observe(el);
// ... some time later
el.remove();
ro.unobserve(el); // <-- is this needed, or does it happen automatically behind the scenes?

Why I'm asking: I'm implementing a React component that observes many children and properly cleaning up the observer for unmounted components would involve non-trivial code, which I want to avoid if it is actually unneeded.

like image 749
amik Avatar asked May 18 '21 07:05

amik


1 Answers

According to the issue in the csswg-drafts repository, today Chrome automatically unobserves the element if you remove it from DOM and delete any references from JS.

let el = document.querySelector("#id");
let ro = new ResizeObserver();
ro.observe(el);
setTimeout(_ => {
  el.remove();
  el = null;
}

Current Chrome code implicitly unobserves element if there are no JS references to it. This is not captured by the specification.

But the issue is still open...

like image 154
mcmimik Avatar answered Nov 05 '22 19:11

mcmimik