intersection observer as a react hook
April 9, 2020, 7:00 AM
A lot of the time, I'll need to know if an element is visibile in the current browser window.
"Back in the day", this was done with a window or document scroll handler. You know, back when no one give a fuck about performance, and just used jQuery for everything.
I was one of those people. Now, I know better.
So, here you go:
const useIntersect = (myRef, callback) => {
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
callback();
}
},{
root: null,
rootMargin: '0px',
threshold: 1.0,
});
return () => {
if (myRef.current) {
observer.unobserve(myRef.current);
observer.disconnect();
}
};
}, []);
};