#atom

Subtitle:

React Query hook for paginated or infinite scrolling data fetching


Core Idea:

useInfiniteQuery extends the base query functionality with specialized support for paginated data and infinite scrolling interfaces, handling the complexity of page tracking and merging.


Key Principles:

  1. Page Management:
    • Tracks and manages multiple pages of data as a unified dataset.
  2. Progressive Loading:
    • Provides controls to load more data while preserving previously loaded pages.
  3. Pagination Metadata:
    • Handles cursor-based or offset pagination with automatic tracking.

Why It Matters:


How to Implement:

  1. Define Query Function:
    • Create a function that accepts a page parameter and returns paginated data.
  2. Configure Options:
    • Set up getNextPageParam to determine how to fetch the next set of data.
  3. Implement UI Controls:
    • Add buttons or scroll handlers that call fetchNextPage/fetchPreviousPage.

Example:

import { useInfiniteQuery } from '@tanstack/react-query';

function Feed() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage
} = useInfiniteQuery({
queryKey: ['feed'],
queryFn: ({ pageParam = 1 }) =>
fetch(/api/feed?page=${pageParam}).then(res => res.json()),
getNextPageParam: (lastPage) =>
lastPage.nextPage || undefined,
});

return (


{data?.pages.map(page =>
page.items.map(post => (

))
)}

<button
onClick={() => fetchNextPage()}
disabled={!hasNextPage || isFetchingNextPage}
>
{isFetchingNextPage
? 'Loading more...'
: hasNextPage
? 'Load more'
: 'No more posts'}


);
}
```

Connections:


References:

  1. Primary Source:
    • TanStack Query documentation on useInfiniteQuery
  2. Additional Resources:
    • "Building Efficient Infinite Lists in React" by Dominik Dorfmeister

Tags:

#react-query #infinite-scroll #pagination #data-fetching #performance


Connections:


Sources: