Skip to content

Instantly share code, notes, and snippets.

@yongdamsh
Created June 7, 2019 08:28
Show Gist options
  • Select an option

  • Save yongdamsh/924c2a7a5b8da317df7331ed204bcc21 to your computer and use it in GitHub Desktop.

Select an option

Save yongdamsh/924c2a7a5b8da317df7331ed204bcc21 to your computer and use it in GitHub Desktop.
React custom hook based on intersectionObserver
import 'intersection-observer';
import { useCallback, useState, useEffect, useRef } from 'react';
const defaultEntry = {
isIntersecting: false,
intersectionRatio: 0
};
const defaultOptions = {};
function useElementVisibility(options = defaultOptions) {
const ref = useRef(null);
const [visibility, setVisibility] = useState(defaultEntry);
function getObserver() {
if (ref.current === null) {
ref.current = new window.IntersectionObserver(entries => {
entries.forEach(entry => {
setVisibility(entry);
});
}, options);
}
return ref.current;
}
const observer = getObserver();
const subscribe = useCallback(
node => {
if (node) {
observer.observe(node);
}
},
[observer]
);
const unsubscribe = () => observer.disconnect();
useEffect(() => {
return () => {
observer.disconnect();
};
}, [observer]);
return [visibility, subscribe, unsubscribe];
}
export default useElementVisibility;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment