usehooks-ts
usehooks-ts copied to clipboard
Fix useIntersectionObserver deps
useEffect has deps elementRef but elementRef never changes it is the .current we are interested in.
+1, would really love to see this merged -- just got bitten by it
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
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>
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.
I can't merge it from here, the repo structure changed since. I'll replicate and mention it.