3

JSFiddle

Code:

export default function App() {
  const spring = useSpring({ from: { opacity: 0 }, to: { opacity: 1 } });

  const [ref] = useInView();

  rerenders++;
  return (
    <div style={{ height: "200vh" }}>
      <div style={{ height: "150vh" }}></div>
      <animated.div
        ref={ref}
        style={{
          height: "50px",
          width: "50px",
          backgroundColor: "red",
          opacity: spring.opacity
        }}
      >
        Hello!
      </animated.div>
    </div>
  );
}

Attaching useInView's ref (a hook from react-intersection-observer) causes constant rerendering of the component. Why is that so?

Using an IntersectionObserver yourself does not do such a thing:

  const ref = useRef<any>();
  
  useLayoutEffect(() => {
    const obs = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry, index) => {
        console.log(entry);
      });
    });
    obs.observe(ref.current);
  }, []);
John Smith
  • 3,863
  • 3
  • 24
  • 42

0 Answers0