Created
October 29, 2019 08:52
-
-
Save udittyagi/edd097021ed8887ca87519a5124d0148 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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