import React, { useEffect, useState } from 'react';
export default function useOnScreen(ref: React.RefObject<any>) {
const [isIntersecting, setIntersecting] = useState(false);
const observer = new IntersectionObserver(([entry]) => setIntersecting(entry.isIntersecting));
useEffect(() => {
observer.observe(ref.current);
return () => {
observer.disconnect();
};
}, []);
return isIntersecting;
}
const SampleComponent = () => {
const ref = useRef<HTMLDivElement>(null)
const isVisible = useOnScreen(ref)
useEffect(() => {
if (isVisible) {
fetchSomething();
}
}, [isVisible]);
const fetchSomething = async () => {
const res = await fetchAPI();
// do some
}
return (
<div ref={ref}>
{/* render fetched data here */}
</div>
)
}