Skip to content

Instantly share code, notes, and snippets.

@udittyagi
Created October 29, 2019 08:52
Show Gist options
  • Save udittyagi/edd097021ed8887ca87519a5124d0148 to your computer and use it in GitHub Desktop.
Save udittyagi/edd097021ed8887ca87519a5124d0148 to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from 'react';
const useIO = (options) => {
const [elements, setElements] = useState([]);
const [entries, setEntries] = useState([]);
const observer = useRef(null);
const { root, rootMargin, threshold } = options || {}
useEffect(() => {
if (elements.length) {
console.log('-----CONNECTING OBSERVER------');
observer.current = new IntersectionObserver((ioEntries) => {
setEntries(ioEntries);
}, {
threshold,
root,
rootMargin
});
elements.forEach(element => {
observer.current.observe(element);
});
}
return () => {
if (observer.current) {
console.log('-----DISCONNECTING OBSERVER------');
observer.current.disconnect();
}
}
}, [elements, root, rootMargin, threshold]);
return [observer.current, setElements, entries];
};
export default useIO;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment