useful-custom-react-hooks
Version:
A collection of useful custom React hooks to simplify common tasks and enhance your React applications.
41 lines (40 loc) • 1.31 kB
JavaScript
import { useState, useEffect, useRef } from 'react';
export const useIntersection = ({ root, rootMargin, threshold, once = false, } = {}) => {
const [isIntersecting, setIntersecting] = useState(false);
const [isObserved, setIsObserved] = useState(false);
const observer = useRef(null);
const ref = useRef(null);
const cd = (entries) => {
for (const entry of entries) {
const intersecting = entry.isIntersecting;
setIntersecting(intersecting);
if (intersecting && once) {
setIsObserved(true);
}
}
};
const options = {
root: root,
rootMargin: rootMargin,
threshold: threshold,
};
useEffect(() => {
observer.current = new IntersectionObserver(cd, options);
}, []);
useEffect(() => {
if (ref.current && observer.current) {
if (isObserved) {
return observer.current.unobserve(ref.current);
}
else {
return observer.current.observe(ref.current);
}
}
return () => {
if (ref.current && observer.current) {
observer.current.unobserve(ref.current);
}
};
}, [isObserved]);
return { isIntersecting, ref };
};