Files
blitzkit/packages/website/src/hooks/useIntersection.ts
T

29 lines
764 B
TypeScript
Raw Normal View History

2025-09-27 16:07:45 -05:00
import { type RefObject, useEffect, useRef } from "react";
2024-07-07 18:01:56 -05:00
interface UseIntersectionOptions extends IntersectionObserverInit {
disabled: boolean;
}
export function useIntersection(
callback: () => void,
ref: RefObject<HTMLElement>,
2025-09-27 16:07:45 -05:00
options?: UseIntersectionOptions
2024-07-07 18:01:56 -05:00
) {
2025-09-27 16:07:45 -05:00
const observer = useRef<IntersectionObserver>(null!);
2024-07-07 18:01:56 -05:00
2024-09-22 22:04:03 -05:00
useEffect(() => {
2024-07-07 18:01:56 -05:00
if (options?.disabled || !ref.current) return;
const rect = ref.current.getBoundingClientRect();
const visible = !(rect.bottom < 0 || rect.top - window.innerHeight >= 0);
2024-07-07 18:19:45 -05:00
if (visible) callback();
2024-07-07 18:01:56 -05:00
2024-07-07 18:19:45 -05:00
observer.current = new IntersectionObserver(callback, options);
observer.current.observe(ref.current);
return () => observer.current!.disconnect();
2024-07-07 18:01:56 -05:00
}, []);
return observer;
}