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:
- Page Management:
- Tracks and manages multiple pages of data as a unified dataset.
- Progressive Loading:
- Provides controls to load more data while preserving previously loaded pages.
- Pagination Metadata:
- Handles cursor-based or offset pagination with automatic tracking.
Why It Matters:
- Performance Optimization:
- Loads data incrementally to improve initial load times and reduce bandwidth usage.
- Improved UX:
- Enables infinite scrolling interfaces for content-heavy applications.
- Reduced Complexity:
- Abstracts away the logic of merging paginated data and tracking pagination state.
How to Implement:
- Define Query Function:
- Create a function that accepts a page parameter and returns paginated data.
- Configure Options:
- Set up getNextPageParam to determine how to fetch the next set of data.
- Implement UI Controls:
- Add buttons or scroll handlers that call fetchNextPage/fetchPreviousPage.
Example:
-
Scenario:
- Loading and displaying a social media feed with infinite scrolling.
-
Application:
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'}
);
}
```
- Result:
- Users can progressively load additional content without manual page tracking.
Connections:
- Related Concepts:
- React Query - Parent library
- useQuery - Base query hook
- Infinite Scrolling - UI pattern
- Broader Concepts:
References:
- Primary Source:
- TanStack Query documentation on useInfiniteQuery
- Additional Resources:
- "Building Efficient Infinite Lists in React" by Dominik Dorfmeister
Tags:
#react-query #infinite-scroll #pagination #data-fetching #performance
Connections:
Sources:
- From: useQuery