Create Instagram Like Infinity Scrolling with React 2025
Create Instagram Like Infinity Scrolling with React 2025
1. Sabse pehle ek React component banao jisme API se images ya posts fetch honge.
2. Infinite scroll ka logic IntersectionObserver
se ya scroll event se likha ja sakta hai.
3. Yahan hum TanStack Query (React Query) ke saath infinite query use karenge.
🔧 Installation:
npm install @tanstack/react-query axios
⚙️ Setup Query Client:
// index.js
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
const queryClient = new QueryClient();
ReactDOM.render(
,
document.getElementById('root')
);
📦 Infinite Scroll Component:
// InfiniteScroll.js
import { useInfiniteQuery } from '@tanstack/react-query';
import axios from 'axios';
import { useRef, useEffect } from 'react';
const fetchPosts = async ({ pageParam = 1 }) => {
const res = await axios.get(`https://api.example.com/posts?page=${pageParam}`);
return res.data;
};
const InfiniteScroll = () => {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
status,
} = useInfiniteQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
getNextPageParam: (lastPage, pages) => {
return lastPage.hasMore ? pages.length + 1 : undefined;
},
});
const loadMoreRef = useRef();
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting && hasNextPage) {
fetchNextPage();
}
});
if (loadMoreRef.current) {
observer.observe(loadMoreRef.current);
}
return () => {
if (loadMoreRef.current) {
observer.unobserve(loadMoreRef.current);
}
};
}, [fetchNextPage, hasNextPage]);
return (
{data?.pages.map((page, i) =>
page.posts.map(post => (
{post.caption}
))
)}
{isFetchingNextPage && Loading more...
}
);
};
export default InfiniteScroll;
📍 Notes:
- API must return a `hasMore` flag to indicate if more data is available.
- Use loading spinners or skeletons for better UX.
- Perfect for image feeds, product lists, or blog posts.