Last active
August 12, 2021 13:46
-
-
Save IvanAdmaers/797c3a2a38fe7242476fa25f3f7cb3ce 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
// React hook useObserver | |
// It also works in next.js | |
import { useEffect, useRef } from 'react'; | |
const useObserver = (ref, callback, options, shouldWork = null) => { | |
const observer = useRef(); | |
useEffect(() => { | |
if (observer.current) { | |
observer.current.disconnect(); | |
} | |
const observerOptions = { | |
root: document, | |
rootMargin: '0px', | |
threshold: 0, | |
...options, | |
}; | |
const cb = (entries) => { | |
if (!entries[0].isIntersecting || shouldWork === false) return; | |
callback(); | |
}; | |
observer.current = new IntersectionObserver(cb, observerOptions); | |
observer.current.observe(ref.current); | |
}, [callback, ref, options, shouldWork]); | |
}; | |
export default useObserver; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment