mirror of
https://github.com/sussy-code/smov.git
synced 2026-04-28 11:32:57 +00:00
43 lines
1 KiB
TypeScript
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 };
|
|
}
|