usehooks-ts icon indicating copy to clipboard operation
usehooks-ts copied to clipboard

Fix useIntersectionObserver deps

Open Guesswhoitis opened this issue 2 years ago • 2 comments

useEffect has deps elementRef but elementRef never changes it is the .current we are interested in.

Guesswhoitis avatar Aug 26 '22 00:08 Guesswhoitis

+1, would really love to see this merged -- just got bitten by it

gregkohn avatar Sep 08 '22 16:09 gregkohn

Even then this won't actually fix it as the current value of a ref changing won't get picked up as a dependency change.

Note that the blog post mentioned as the source in the hook docs has switched to using useState for this exact reason image our typed version looks like

const useIntersectionObserver = (options?: IntersectionObserverInit): [Dispatch<HTMLElement>, IntersectionObserverEntry | null] => {
  const [entry, setEntry] = useState<IntersectionObserverEntry | null>(null);
  const [node, setNode] = useState<HTMLElement | null>(null);

  const observer = useRef<IntersectionObserver | null>(null);

  useEffect(() => {

      if (observer.current) observer.current.disconnect();

      observer.current = new IntersectionObserver(([entry]) => setEntry(entry), options);

      const {current: currentObserver} = observer;

      if (node) currentObserver.observe(node);

      return () => currentObserver.disconnect();
    },
    [node, JSON.stringify(options)]
  );

  return [setNode, entry];
};

And is used as such

const [setRef, intersection] = useIntersectionObserver();

useEffect(() => {
    console.log(intersection?.isIntersecting);
}, [intersection?.isIntersecting]);
//...

return <div ref={setRef}>...</div>

hailwood avatar Sep 22 '22 02:09 hailwood

Hi guys, thanks for all. I'll merge it now, and plan to add the second version with the Dispatch function as a ref in the v3 because it introduces a breaking change.

juliencrn avatar Oct 12 '22 23:10 juliencrn

I can't merge it from here, the repo structure changed since. I'll replicate and mention it.

juliencrn avatar Oct 13 '22 00:10 juliencrn