smov/src/pages/discover/hooks/useIntersectionObserver.tsx
2025-02-28 22:21:36 -07:00

43 lines
1 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
interface IntersectionObserverOptions {
root?: Element | null;
rootMargin?: string;
threshold?: number | number[];
}
export function useIntersectionObserver(
options: IntersectionObserverOptions = {},
) {
const [isIntersecting, setIsIntersecting] = useState(false);
const [hasIntersected, setHasIntersected] = useState(false);
const targetRef = useRef<Element | null>(null);
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => {
setIsIntersecting(entry.isIntersecting);
if (entry.isIntersecting) {
setHasIntersected(true);
}
},
{
...options,
rootMargin: options.rootMargin || "200px 0px",
},
);
const currentTarget = targetRef.current;
if (currentTarget) {
observer.observe(currentTarget);
}
return () => {
if (currentTarget) {
observer.unobserve(currentTarget);
}
};
}, [options]);
return { targetRef, isIntersecting, hasIntersected };
}