#How can I resolve this cleanup ref issue?

7 messages · Page 1 of 1 (latest)

oak pivot
#

Warning: The ref value 'lastBookmarkRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'lastBookmarkRef.current' to a variable inside the effect, and use that variable in the cleanup function.

useEffect(() => {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        setPage((prevPage) => prevPage + 1)
      }
    })

    if (lastBookmarkRef.current) {
      observer.observe(lastBookmarkRef.current)
    }

    return () => {
      if (lastBookmarkRef.current) {
        observer.unobserve(lastBookmarkRef.current)
      }
    }
  }, [])
timid geyser
#

lastBookmarkRef is an object like { current: ... }

#

react can, and does, mutate ref objects

#

so you need to be sure that when you're cleanup runs, it's not running on some other html element that react has assigned to lastBookmarkRef.current

#

additionally, since you didn't declare any dependencies for your useEffect the intersection observer will not update correctly on re-render (on further googling, this statement is wrong)

autumn flax
timid geyser
#

I think you want something more like

const observer = new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) {
    setPage((prevPage) => prevPage + 1);
  }
});
useEffect(() => {
  if (lastBookmarkRef.current) {
    const observee = lastBookmarkRef.current;
    observer.observe(observee);
    return () => observer.unobserve(observee);
  }
  return;
}, []);