@modern-kit/react
Version:
62 lines (58 loc) • 1.87 kB
JavaScript
;
var React = require('react');
var hooksUsePreservedCallback = require('../usePreservedCallback/index.cjs');
var utils = require('@modern-kit/utils');
function useIntersectionObserver({
onIntersectStart = utils.noop,
onIntersectEnd = utils.noop,
enabled = true,
calledOnce = false,
root = null,
threshold = 0,
rootMargin = "0px 0px 0px 0px"
} = {}) {
const [isIntersecting, setIsIntersecting] = React.useState(false);
const [hasIntersected, setHasIntersected] = React.useState(false);
const observerRef = React.useRef(null);
const calledCount = React.useRef(0);
const intersectionObserverCallback = hooksUsePreservedCallback.usePreservedCallback(
([entry], observer) => {
if (!entry) return;
const targetElement = entry.target;
setIsIntersecting(entry.isIntersecting);
if (entry.isIntersecting) {
calledCount.current += 1;
setHasIntersected(true);
onIntersectStart(entry);
} else if (isIntersecting) {
calledCount.current += 1;
onIntersectEnd(entry);
}
if (calledOnce && calledCount.current > 1) {
observer.unobserve(targetElement);
}
}
);
const targetRef = React.useCallback(
(node) => {
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
if (node == null || !enabled) return;
observerRef.current = new IntersectionObserver(
intersectionObserverCallback,
{
threshold,
root,
rootMargin
}
);
observerRef.current.observe(node);
},
[enabled, threshold, root, rootMargin, intersectionObserverCallback]
);
return { ref: targetRef, isIntersecting, hasIntersected };
}
exports.useIntersectionObserver = useIntersectionObserver;
//# sourceMappingURL=index.cjs.map