Is it safe to call observe method of a ResizeObserver multiple times on an element?

Viewed 415

I have a situation in react, where I need to observer the size of each child element of a react component. I have created a new ResizeObserver.

ro = new ResizeObserver((entries) => {
  entries.forEach((i) => {
    console.log(i.contentRect.height);
    // some action on resize
  });
});

And to observer all children I ran a loop in componentDidMount

Array.prototype.map.call(this.elementRef.current.children, (item) => {
        this.ro.observe(item);
      });

I also added code to unobserve in componentDidUnmount

Array.prototype.map.call(this.elementRef.current.children, (item) => {
            this.ro.unobserve(item);
          });
    

Now, I have a scenario that children can increase dynamically without triggering remount. So I am adding componentDidMount code to componentDidUpdate. I am wondering if that is safe or will I have to identify which children currently not being observed and then only run observe on new children. If so, how can I do that?

1 Answers

It is safe to call observe multiple times on the same element as noted in the specs.

Consider observing the parent container instead of the children if the children sizing affect the parent.

Related