Tillitsdone
down Scroll to discover

React Query: Master Pagination & Infinite Scroll

Learn how to implement efficient pagination and infinite scrolling in React applications using React Query.

Discover best practices, code examples, and pro tips for better UX.
thumbnail

A futuristic abstract interior with floating geometric shapes featuring a gradient of canary yellow blending into cream white dramatic volumetric lighting casting long shadows viewed from a low angle perspective looking upward high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Ever found yourself wrestling with pagination in React? You’re not alone. Today, let’s dive into how React Query makes handling paginated data and infinite scrolling a breeze. Trust me, once you see how elegant this solution is, you’ll wonder why you didn’t try it sooner.

The Traditional Pagination Headache

We’ve all been there - managing page numbers, loading states, and cached data while trying to keep our UI smooth and responsive. It’s like trying to juggle while riding a unicycle. Not fun.

Abstract space station corridor with smooth metallic surfaces reflecting iridescent light beams dominant colors of bright orange transitioning to deep blue photographed from a straight-on perspective with strong leading lines high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Enter React Query

React Query transforms this complexity into something beautifully simple. Let’s look at how we can implement both traditional pagination and infinite scrolling.

Traditional Pagination Implementation

Here’s a real-world example that you can drop into your project:

const usePaginatedPosts = (page) => {
return useQuery({
queryKey: ['posts', page],
queryFn: () => fetchPosts(page),
keepPreviousData: true
});
}
function PostList() {
const [page, setPage] = useState(1);
const { data, isLoading, isFetching } = usePaginatedPosts(page);
if (isLoading) return <div>Loading posts...</div>;
return (
<div>
{data.posts.map(post => (
<PostCard key={post.id} post={post} />
))}
<div>
<button
onClick={() => setPage(old => Math.max(old - 1, 1))}
disabled={page === 1}
>
Previous Page
</button>
<span>Page {page}</span>
<button
onClick={() => setPage(old => old + 1)}
disabled={!data.hasMore}
>
Next Page
</button>
</div>
</div>
);
}

Ethereal cloud formations with streaming light rays piercing through colors of bright minimalist yellow and crisp white against off-black background captured from a diagonal upward angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Infinite Scrolling Magic

Now, let’s look at how React Query handles infinite scrolling - it’s surprisingly straightforward:

const useInfinitePosts = () => {
return useInfiniteQuery({
queryKey: ['posts'],
queryFn: fetchPostPage,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
}
function InfinitePostList() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage
} = useInfinitePosts();
return (
<div>
{data.pages.map(page => (
page.posts.map(post => (
<PostCard key={post.id} post={post} />
))
))}
<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load More'
: 'Nothing more to load'}
</button>
</div>
);
}

The beauty of React Query’s solution lies in its automatic handling of cache invalidation, loading states, and error boundaries. It’s like having a smart assistant that manages all the complex state logic while you focus on building great user experiences.

Pro Tips

  1. Always use keepPreviousData: true for smoother transitions between pages
  2. Implement proper error boundaries for production-ready code
  3. Consider prefetching the next page for instant loading
  4. Use suspense: true for even cleaner loading states

React Query transforms pagination from a necessary evil into a delightful implementation detail. Whether you’re building a simple blog or a complex data table, these patterns will serve you well.

Stone textured abstract surface with flowing patterns bright iridescent colors of orange and blue reflecting off smooth curves viewed from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.