Skip to content

Instantly share code, notes, and snippets.

@IvanAdmaers
Last active August 12, 2021 13:46
Show Gist options
  • Save IvanAdmaers/797c3a2a38fe7242476fa25f3f7cb3ce to your computer and use it in GitHub Desktop.
Save IvanAdmaers/797c3a2a38fe7242476fa25f3f7cb3ce to your computer and use it in GitHub Desktop.
// 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