Pagination and Infinite Scroll
×


Pagination and Infinite Scroll

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>
  );
}
  • 🔁 keepPreviousData helps 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>
  );
}
  • 📦 useInfiniteQuery tracks all loaded pages
  • 🧠 getNextPageParam determines when to stop loading

🧠 Optional: Auto-Trigger on Scroll

You can trigger infinite fetches as the user scrolls using an IntersectionObserver or libraries like react-intersection-observer:


const { ref, inView } = useInView();

useEffect(() => {
  if (inView && hasNextPage) {
    fetchNextPage();
  }
}, [inView, hasNextPage]);

📋 Pagination vs Infinite Scroll: Comparison

FeaturePaginationInfinite Scroll
User ControlHigh (page numbers, navigation)Low (auto-loads content)
PerformanceBetter for large datasetsCan get heavy without unmounting
Use CaseAdmin panels, tablesFeeds, 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’s useQuery 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!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat