2024-09-21 20:26:58 -05:00
|
|
|
import { type RefObject, useEffect, useRef, useState } from 'react';
|
2024-08-26 21:47:14 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Thanks GuCier!
|
|
|
|
|
*
|
|
|
|
|
* https://stackoverflow.com/a/65008608/12294756
|
|
|
|
|
*/
|
2024-09-08 10:11:24 -05:00
|
|
|
export function useOnScreen(ref: RefObject<HTMLElement>) {
|
2024-08-26 21:47:14 -05:00
|
|
|
const [isIntersecting, setIntersecting] = useState(false);
|
|
|
|
|
const observer = useRef<IntersectionObserver>();
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
observer.current = new IntersectionObserver(([entry]) =>
|
|
|
|
|
setIntersecting(entry.isIntersecting),
|
|
|
|
|
);
|
|
|
|
|
}, [ref]);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (!ref.current) return;
|
|
|
|
|
|
|
|
|
|
observer.current?.observe(ref.current);
|
|
|
|
|
return () => observer.current?.disconnect();
|
|
|
|
|
}, [ref]);
|
|
|
|
|
|
|
|
|
|
return isIntersecting;
|
|
|
|
|
}
|