useIntersection is not working on first load with conditional reference
What is the current behavior?
IntersectionObserver didn't be register correctly on first load
Steps to reproduce it and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have extra dependencies other than react-use. Paste the link to your JSFiddle or CodeSandbox example below:
https://codesandbox.io/s/bad-example-ref-does-not-handle-unmount-forked-7sl1qd?file=/index.js
What is the expected behavior? IntersectionObserver should be registered correctly and can correctly show the Intersecting boolean
A little about versions:
- OS: MacOS
- Browser (vendor and version): Chrome
- React: 18.2.0
-
react-use: 17.4.0 - Did this worked in the previous package version?
Suggestions:
refs: https://github.com/facebook/react/issues/14387#issuecomment-503616820
It seems that adding ref.current on the deps array is not a correct syntax and maybe need to revamp to useCallback hooks
For the others have the same issue, change the useIntersection to this
import { useCallback, useEffect, useState } from "react";
export const useIntersection = (options: IntersectionObserverInit) => {
const [intersection, setIntersection] = useState<IntersectionObserverEntry | null>(null);
const [element, setElement] = useState<HTMLElement | null>(null);
const captureIntersectionElement = useCallback((element: HTMLElement | null) => {
element && setElement(element);
}, []);
useEffect(() => {
if (element == null || typeof IntersectionObserver !== "function") return;
const handler = (entries: IntersectionObserverEntry[]) => {
setIntersection(entries[0]);
};
const observer = new IntersectionObserver(handler, options);
observer.observe(element);
return () => {
setIntersection(null);
observer.disconnect();
};
}, [options, element]);
return { captureIntersectionElement, element, intersection };
};