To achieve this goal, you need two components.
Intersection Observer API
in your React app, you should use the useInView hook from the
react-intersection-observer
library .
import React from 'react'; import { useQuery } from "react-query"; import { useInView } from "react-intersection-observer"; const PostComponent = ({ post }) => { const { ref, inView } = useInView(); const { data, isLoading, error } = useQuery( ["comments", post.id], () => fetchComments(post.id), // the useQuery hook will fetch only when inView is enabled { enabled: inView } ); return ( <div ref={ref}> {isLoading && <div>Loading comments...</div>} {error && <div>Error fetching comments</div>} {data && ( <div> <p>{post.title}</p>{" "} </div> )} </div> ); };