3
votes

Recently I've been using Intersection Observers in React (16.4+) as follows:

const myRef = React.useRef(null);

React.useLayoutEffect(() => {
  const observer = new IntersectionObserver(
    doWork,
    { rootMargin: "0px 0px 0px 0px" }
  );

  observer.observe(myRef.current)
}, [])

Generally in React we're told to always return a cleanup function from our effect hooks if those hooks are setting up functions like window.addEventListener:

return () => window.removeEventListener('event', cb); // more cleanup

Should I be unobserve'ing myRef.current in a similar way? Or is that not strictly required in the same way it is for window event listeners?

I haven't found anything in the w3c spec regarding this, I've also been performance profiling my components and I haven't seen any negative results of not explicitly observing either.

Is there any consensus on this?

It might not be strictly required if the observed element is removed from the DOM anyway (unlike for installing listeners on globals like window), but yes it's definitely a best practice. - Bergi
This SO post is more about MutationObservers, but the idea is similar: Don't worry too much about it, since it will be garbage collected when the DOM Element is removed. stackoverflow.com/a/51106262/2661744 I guess it could be best practice to save some work for your garbage collector though. - joshkarges