Cursor vs offset pagination: which should a frontend use for infinite scroll?
IntermediateNetworking and HTTP interview questionBy UIRound, updated 23 November 2026
Short answer
Use cursor pagination for infinite scroll. An offset says "skip 40 rows", so when new rows arrive at the top while the user scrolls, the next page repeats items, and deletions silently skip some. A cursor says "continue after this item", so inserts elsewhere do not move it. Offset still suits numbered pages, jump-to-page and total counts. Either way, the client should dedupe items by id.
What goes wrong with offsets in a feed
A feed sorted newest first, 20 items per page:
- The user loads page 1:
GET /posts?offset=0&limit=20returns posts 1 to 20. - While they read, three new posts are published at the top.
- They scroll and the client asks for
offset=20. Everything has shifted down by three, so the 21st row is now post 18, and posts 18, 19 and 20 appear a second time.
Deletions do the opposite: if two posts on page 1 are deleted, offset=20 starts two items too late and the user never sees them. Nothing errors, so these bugs reach production and show up as "I saw the same post twice" reports.
A cursor request, GET /posts?after=<cursor>&limit=20, asks for the 20 posts that sort after the last one the client has. New posts at the top do not change what comes after post 20. The client-server API design guide covers the server side: what a cursor encodes, response shapes and the cost of deep offsets in the database.
The frontend decision
| The screen needs | Use |
|---|---|
| Infinite scroll or "Load more" on a feed, chat, notifications, activity log | Cursor |
| Numbered pages, "jump to page 7", a page number in the URL | Offset or page number |
| "1,284 results" and a last page | Offset, or a cursor API that also returns a count |
| A table sorted and filtered by many columns, mostly static data | Offset is fine |
| Data that changes while the user is reading it | Cursor |
Many products use both: search results with numbered pages, and a home feed with cursors. If you control the API, pick per screen rather than once for the whole app.
Building infinite scroll on a cursor API
A response shape the client can rely on:
{ "items": [{ "id": "p21", "title": "..." }], "nextCursor": "eyJ0IjoiMjAyNi0x...", "hasMore": true }Treat the cursor as opaque. Do not parse it, build it or do arithmetic on it; pass back exactly what the server sent. GraphQL APIs that follow the Relay connection spec expose the same idea as pageInfo { hasNextPage endCursor } with first and after arguments.
With TanStack Query v5, the cursor is the page param:
const feed = useInfiniteQuery({
queryKey: ["feed", filters], // a new filter means a new list, starting from no cursor
queryFn: ({ pageParam, signal }) => fetchFeed({ cursor: pageParam, filters, signal }),
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => (lastPage.hasMore ? lastPage.nextCursor : undefined),
});Then trigger fetchNextPage() when a sentinel element near the bottom becomes visible, using an IntersectionObserver with a rootMargin so the next page starts loading before the user reaches the end. Practise both halves in infinite scrolling with IntersectionObserver and a useInfiniteQuery() clone.
Things the client must handle whichever library you use:
- One request at a time per list. The sentinel can fire again before the first request returns. Skip the call while one is in flight (
isFetchingNextPage), or you append the same page twice. - Reset on query change. A new search term or filter invalidates the cursor. Put the filters in the query key, or clear the pages and cursor yourself, and ignore any response for the old query that arrives late.
- Stop at the end. When
hasMoreis false, disconnect the observer and show an end-of-list state instead of retrying forever. - Errors at the bottom. Keep the pages already loaded and show a retry button where the next page would be. Do not throw away the list.
Dedupe by id anyway
Cursors remove the main source of duplicates, but not all of them. Items can still repeat when a ranking changes between requests, when a real-time event inserts an item the next page also returns, or when an API you do not control still uses offsets underneath. Deduping on the client is cheap insurance:
function flattenPages(pages: { items: Post[] }[]): Post[] {
const seen = new Set<string>();
const out: Post[] = [];
for (const page of pages) {
for (const post of page.items) {
if (seen.has(post.id)) continue; // first occurrence keeps its place
seen.add(post.id);
out.push(post);
}
}
return out;
}Stable ids matter for rendering too. Use post.id as the React key, never the array index, so a removed duplicate does not shift every row's state. A useCursorPagination() hook combines dedupe, reset and stale-response handling.
Dedupe fixes repeats, not skips. If you are stuck with an offset API on live data, ask for a snapshot bound on the first request, such as ?createdBefore=<time of first load>, so later inserts cannot shift the pages.
Sorting must be stable
Pagination of either kind is only correct when the sort order is total and does not change underneath you.
- Add a unique tie-breaker. Sorting by
createdAtalone lets two posts with the same timestamp come back in a different order on each query, which causes duplicates and skips even with no writes. Sort by(createdAt, id)and encode both in the cursor. - Beware mutable sort keys. Sorting by score, likes or "hot" means items move while the user scrolls. Ranked feeds usually snapshot the ranking for a session on the server and return a cursor into that snapshot. As a client, you just dedupe and trust the cursor.
Newer items, going back, and long sessions
- New items at the top. Do not insert them into a list the user is reading; it moves content under their finger. Fetch newer items with a separate
before/sincerequest and show a "New posts" pill, as in the X home timeline design. - Back navigation. Keep loaded pages in a cache keyed by the list so going back to the feed restores the same items and scroll position, instead of refetching page 1 and losing the place.
- Very long sessions. Hundreds of loaded items mean a large DOM. Render with list virtualisation, and consider capping pages in memory (TanStack Query's
maxPages, which also needsgetPreviousPageParamso dropped pages can be refetched when the user scrolls back). - Deep links. A page number in the URL is easy to share and to crawl. A cursor in the URL works but may expire. For SEO, back an infinite list with crawlable paginated URLs.
Follow-up questions interviewers ask
Can you show "Page 3 of 50" with cursor pagination?
Not exactly, since a cursor has no page number. You can show a total if the API returns one, or "Showing 60 results" with "Load more". If the product truly needs numbered pages, offset is the honest choice for that screen.
Why not just refetch everything when new items arrive?
It is expensive, it resets scroll and focus, and the user loses their place. Fetch only the newer items and let the user choose to see them.
What if the item the cursor points to is deleted?
A well-built cursor encodes sort values, not a row reference, so the server continues from "after (createdAt, id)" whether or not that row still exists. If the server rejects an expired cursor, restart from the top and dedupe what you already show.
Infinite scroll or a "Load more" button?
Infinite scroll suits browsing feeds. A button suits lists with a footer, keyboard and screen reader users who need predictable focus, and pages where the user wants to stop. Both use the same cursor API, as in the news feed design.
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Build
useCursorPagination(): load pages by cursor, drop duplicates, reset when the query changes and ignore stale responsesMedium40 min - Build a TanStack Query-style
useInfiniteQuery(): page params,fetchNextPage,hasNextPage,maxPagesand refetchMedium50 min - Build infinite scrolling using
IntersectionObserverMedium35 minFree - Implement server-side pagination with sorting and filteringMedium40 min
- Design a news feed with infinite scrollHard60 minFree
- Design the X (Twitter) home timeline: For You and Following tabs, a new-posts pill, infinite scroll and optimistic likesHard55 min