Skip to main content
Version: v10.0.0

Pagination and Infinite Scroll

Infinite lists are where request-level caches struggle most with real-time data. A new post has to be placed inside the right page, a deleted one leaves a gap, and a refetch has to reload every page without the list jumping. With the db, pages are a view over a live, ordered query. The loader knows how to fetch the next backend page, and useLiveInfiniteQuery decides how much of the result to show.

This guide turns Teamboard's feed into an infinite list that stays live.

What you'll learn
  1. How to declare a paginated loader with a cursor, or with a limit.
  2. Why a paginated loader must send every condition and order of a query.
  3. How to build "Load more" and scroll-triggered lists with useLiveInfiniteQuery.
  4. Why UI pages are independent of backend pages.
  5. How loaded pages stay live, and which new rows join them.
  6. How to paginate outside React, and how to read GraphQL Relay connections.

A paginated loader​

A loader becomes paginated when it declares cursor or limit. Teamboard's feed endpoint returns a cursor:

const getTeamPosts = client.createRequest<{
response: { items: PostSummary[]; next: string | null };
queryParams?: { status?: "draft" | "published"; sort?: string; cursor?: string };
}>()({ endpoint: "/teams/:teamId/posts" });

const PostSummary = collection(PostSummarySchema, { key: "id", version: "updatedAt" }).load(getTeamPosts, {
rows: (response) => response.items,
// Reads the next page's cursor. `null` or `undefined` means there are no more pages.
cursor: (response) => response.next,
// Sends a cursor to load the page after it
page: (cursor) => ({ queryParams: { cursor } }),
where: {
teamId: { eq: (teamId) => ({ params: { teamId } }), required: true },
status: { eq: (status) => ({ queryParams: { status } }) },
},
orderBy: { createdAt: (direction) => ({ queryParams: { sort: `createdAt:${direction}` } }) },
});

useLiveQuery already pages through it: data holds every loaded row, and fetchNextPage loads the next backend page.

const { data, hasNextPage, fetchNextPage } = useLiveQuery(
db.postSummary.where((post) => eq(post.teamId, teamId)).orderBy((post) => post.createdAt, "desc"),
);

Every condition goes to the server​

A page is a slice of the server's result. Filtering or sorting one page on the client gives wrong results: the second page would hold rows that belong on the first. So a paginated loader serves a query only when it can send every condition and every order, and anything else does not compile:

useLiveQuery(
db.postSummary.where((post) => eq(post.teamId, teamId)).where((post) => gt(post.likes, 10)),
);
// The paginated loader cannot send `likes`, so no loader can serve the query

Declare the filter on the loader, add a second loader that is not paginated, or filter what is on screen with a .local() query.


Infinite scroll with useLiveInfiniteQuery​

useLiveInfiniteQuery shows an ordered query as pages of a fixed size:

import { eq } from "@hyper-fetch/db";
import { useLiveInfiniteQuery } from "@hyper-fetch/react";

const TeamFeed = ({ teamId }: { teamId: string }) => {
const { pages, hasNextPage, fetchNextPage, isFetchingNextPage, status } = useLiveInfiniteQuery(
db.postSummary.where((post) => eq(post.teamId, teamId)).orderBy((post) => post.createdAt, "desc"),
{ pageSize: 20 },
);

if (status === "loading") return <p>Loading posts...</p>;

return (
<div className="flex flex-col gap-4">
{pages.map((page, index) => (
<div key={index} className="flex flex-col gap-2">
{page.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
))}
{hasNextPage && (
<button disabled={isFetchingNextPage} onClick={() => fetchNextPage()}>
{isFetchingNextPage ? "Loading..." : "Load more"}
</button>
)}
</div>
);
};
  • The query must have orderBy, so a page never shifts between renders. Without it, it does not compile. The key breaks ties.
  • data holds the rows of every shown page, and pages splits them into arrays of pageSize.
  • hasNextPage is true while the db holds rows past the window, or the loader reports another backend page.
  • Calling fetchNextPage() twice while a page loads loads one page, so a double scroll event is harmless.

Loading while scrolling​

Replace the button with an element at the end of the list, and load when it scrolls into view:

const ScrollingFeed = ({ teamId }: { teamId: string }) => {
const { data, hasNextPage, fetchNextPage } = useLiveInfiniteQuery(
db.postSummary.where((post) => eq(post.teamId, teamId)).orderBy((post) => post.createdAt, "desc"),
{ pageSize: 20 },
);
const sentinel = useRef<HTMLDivElement>(null);

useEffect(() => {
const element = sentinel.current;
if (!element || !hasNextPage) return undefined;
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) fetchNextPage();
});
observer.observe(element);
return () => observer.disconnect();
}, [hasNextPage, fetchNextPage]);

return (
<div>
{data?.map((post) => (
<PostCard key={post.id} post={post} />
))}
<div ref={sentinel} />
</div>
);
};

UI pages are not backend pages​

pageSize is the size of your pages. The backend's page size is whatever its endpoint returns:

  • When the db already holds rows past the window, the next page shows at once, with no request.
  • Otherwise a cursor loader loads backend pages until the db holds one row past the window, or the backend has no more. A backend page of 50 fills two and a half UI pages of 20.
  • A loader with limit and no cursor is sent the window size plus one, and the previous window stays on screen while the wider one loads.
  • A loader that is not paginated has loaded every row already. The window only limits what is shown.
const getTopPosts = client.createRequest<{ response: PostSummary[]; queryParams?: { limit?: number } }>()({
endpoint: "/teams/:teamId/top-posts",
});

const TopPost = collection(PostSummarySchema, { key: "id" }).load(getTopPosts, {
where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } },
// Uses the db-wide `orderBy` notation from createDb, see the Loaders guide
orderBy: { likes: true },
// Pages of 10: sends limit=11, then limit=21, ...
limit: (limit) => ({ queryParams: { limit } }),
});

Two components showing the same query share its loaded pages and its requests, and each keeps its own number of pages.


Pages that stay live​

The window is a view over a live query, so syncs and writes reach it like any other view:

  • An insert inside the window pushes the last row to the next page.
  • A delete pulls the next held row in. When that leaves the window short and the loader has more, the next backend page loads.
  • An update that changes a sort field moves the row to its new position, across pages if needed.

New rows follow one rule. The db only knows the rows of the pages it loaded, so a new row joins a paginated list when it sorts before the last loaded row, or anywhere once the backend has no more pages. A row that sorts past the loaded range arrives with the page that contains it. This needs an orderBy on the query: without one, a new row never joins a paginated list that has more pages.

Refetching every page​

A refetch, whether from refetch(), a reconnect or a stale list when the window regains focus, reloads every loaded page, in order from the first, following each new cursor:

  • The rows stay on screen until the last page is back, so the list does not jump while it reloads.
  • Rows none of the pages returned leave the list, so a post deleted on the server disappears even without a delete event.
  • When a page fails, the refetch stops, the loaded rows stay and the query reports the error in error. The next refetch starts again from the first page.

Outside React​

useLiveInfiniteQuery wraps query.infinite(), which works anywhere:

const feed = db.postSummary
.where((post) => eq(post.teamId, "t1"))
.orderBy((post) => post.createdAt, "desc")
.infinite({ pageSize: 20 });

const unsubscribe = feed.subscribe(() => render(feed.getSnapshot().pages));
await feed.fetchNextPage();

Pages load for subscribers only, as queries do: fetchNextPage() on an infinite query nobody subscribes to does nothing.


GraphQL Relay connections​

Many GraphQL APIs paginate with Relay connections: edges, node and pageInfo. relayConnection() reads the rows and the next cursor from one, so you only add how to send the cursor:

import { relayConnection } from "@hyper-fetch/db";

collection(PostSummarySchema, { key: "id" }).load(getPostsConnection, {
...relayConnection((response: PostsResponse) => response.posts),
page: (after) => ({ payload: { after } }),
});

The cursor is pageInfo.endCursor while pageInfo.hasNextPage is true. Empty edges are skipped.

Coming from useInfiniteFetch or React Query
  • useInfiniteFetch and React Query's useInfiniteQuery store pages of responses. A socket event or a mutation has to find the item inside the right page, or refetch every page.
  • useLiveInfiniteQuery stores rows, and pages are a window over them. Events and writes update one row, and the window recalculates.
  • Use useInfiniteFetch for lists nothing else changes, such as an activity log. Use the db when the items also change from sockets, writes or other views.

Endless and live!

Teamboard's feed scrolls forever and never goes stale.

  • You can declare cursor and limit loaders, and know why they must send every condition and order.
  • You can build "Load more" and scroll-triggered lists with useLiveInfiniteQuery.
  • You can pick a UI page size independent of the backend's.
  • You can rely on pages that stay live, and know which new rows join them.
  • You can refetch every page without the list jumping.
  • You can paginate outside React and read Relay connections.

Next steps​

List and Detail Views
Show summaries in lists and full records on detail pages, with every view in step.