Pagination and Infinite Scroll
0 817
📚 Pagination and Infinite Scroll in React
Displaying large datasets all at once can harm performance and user experience. That’s where pagination and infinite scrolling come in — allowing you to load data in chunks. With TanStack Query and React 19, implementing both strategies is efficient, clean, and scalable. Let’s explore both approaches with real code examples. âš›ï¸ðŸ”🔢 What Is Pagination?
Pagination means dividing content into pages. Each request loads a specific subset of data — page 1, page 2, and so on.âš™ï¸ Basic Pagination Setup with TanStack Query
import { useQuery } from '@tanstack/react-query';
function fetchPosts(page = 1) {
return fetch(`/api/posts?page=${page}`).then(res => res.json());
}
function PaginatedPosts() {
const [page, setPage] = useState(1);
const { data, isLoading } = useQuery({
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
keepPreviousData: true,
});
return (
<div>
{isLoading ? <p>Loading...</p> : (
<ul>
{data.posts.map(post => <li key={post.id}>{post.title}</li>)}
</ul>
)}
<button onClick={() => setPage(old => Math.max(old - 1, 1))} disabled={page === 1}>Previous</button>
<button onClick={() => setPage(old => old + 1)} disabled={!data?.hasMore}>Next</button>
</div>
);
}
- ðŸ”
keepPreviousDatahelps retain the previous page while fetching the new one - 📄 Query key includes the page number to avoid cache conflicts
â™¾ï¸ What Is Infinite Scrolling?
Infinite scrolling loads more data as the user scrolls down — often used in feeds, search results, or galleries.🚀 Infinite Scroll with useInfiniteQuery
import { useInfiniteQuery } from '@tanstack/react-query';
function fetchPages({ pageParam = 1 }) {
return fetch(`/api/posts?page=${pageParam}`).then(res => res.json());
}
function InfinitePostList() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['infinitePosts'],
queryFn: fetchPages,
getNextPageParam: (lastPage, pages) => {
return lastPage.hasMore ? pages.length + 1 : undefined;
},
});
return (
<div>
{data?.pages.map((page, i) => (
<React.Fragment key={i}>
{page.posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
</React.Fragment>
))}
<button
disabled={!hasNextPage || isFetchingNextPage}
onClick={() => fetchNextPage()}
>
{isFetchingNextPage ? 'Loading more...' : hasNextPage ? 'Load More' : 'No More Posts'}
</button>
</div>
);
}
- 📦
useInfiniteQuerytracks all loaded pages - ðŸ§
getNextPageParamdetermines when to stop loading
🧠Optional: Auto-Trigger on Scroll
You can trigger infinite fetches as the user scrolls using anIntersectionObserver or libraries like react-intersection-observer:
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage]);
📋 Pagination vs Infinite Scroll: Comparison
| Feature | Pagination | Infinite Scroll |
| User Control | High (page numbers, navigation) | Low (auto-loads content) |
| Performance | Better for large datasets | Can get heavy without unmounting |
| Use Case | Admin panels, tables | Feeds, galleries, blogs |
| SEO Friendly | ✅ | ⌠(unless server-rendered carefully) |
✅ Best Practices
- â³ Use loading placeholders between pages
- â™»ï¸ Handle empty states and no more results
- 🚫 Prevent duplicate queries with proper keys
- 🧼 Reset data on unmount if needed using
queryClient.removeQueries()
🚀 Final Thoughts
Both pagination and infinite scroll are essential UX strategies for working with large datasets in React. With TanStack Query’suseQuery and useInfiniteQuery, you can handle both efficiently — complete with caching, loading states, and error handling. Choose what fits your product and users best — or combine both! ðŸ”âš›ï¸If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments