Infinite scroll loads the next batch of items when the user scrolls near the bottom. Done well, it feels seamless. Done poorly, it duplicates rows, loads twice, or breaks accessibility. This recipe shows the IntersectionObserver-based approach, which is the right one today: no scroll-event listeners, no debounce hacks.
The pieces
Three building blocks:
- A hook that holds the appended items and knows how to load more.
- A sentinel element rendered after the last item.
- An IntersectionObserver that fires
loadMorewhen the sentinel scrolls into view.
The hook
Append-only state. Each new page is added to the end of the existing array. GoRest v3 does not use page numbers here. Each list answer has meta.next_cursor and meta.has_more. Send the cursor back as page[after] to get the next page.
import { useEffect, useRef, useState } from "react";
function useInfiniteUsers() {
const [items, setItems] = useState([]);
const [cursor, setCursor] = useState(null); // cursor to send with the next fetch
const [hasMore, setMore] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const loading = useRef(false);
async function loadMore() {
if (loading.current || !hasMore) return;
loading.current = true;
setBusy(true);
const url = new URL("https://gorest.co.in/public/v3/users");
url.searchParams.set("page[size]", "20");
if (cursor) url.searchParams.set("page[after]", cursor);
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`Got ${res.status}`);
const { data, meta } = await res.json();
setItems(prev => [...prev, ...data]);
setCursor(meta.next_cursor);
setMore(meta.has_more);
} catch (err) {
setError(err);
} finally {
loading.current = false;
setBusy(false);
}
}
return { items, hasMore, busy, error, loadMore };
}Three details that matter:
- The cursor is opaque. Do not decode it or build it yourself. Pass
meta.next_cursorback exactly as you got it. - The
loadingref guard insideloadMore. Without it, an over-eager observer fires multiple loads before the first response arrives. A ref changes at once, while state changes only on the next render. - Stop when
meta.has_moreis false. Do not wait for an empty page. - Cursor paging does not skip or repeat rows when new rows are added while the user scrolls. Page numbers can.
The sentinel and observer
Render an empty li after the last item. Observe it. When it scrolls into view, load more.
function UserFeed() {
const { items, hasMore, busy, loadMore } = useInfiniteUsers();
const sentinel = useRef(null);
const latest = useRef(loadMore);
latest.current = loadMore; // the observer always calls the newest loadMore
useEffect(() => {
if (!sentinel.current) return;
const io = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) latest.current();
}, { rootMargin: "200px" });
io.observe(sentinel.current);
return () => io.disconnect();
}, [hasMore, items.length]); // new observer after each page, so a sentinel still in view loads again
return (
<ul>
{items.map(u => <li key={u.id}>{u.name} ({u.email})</li>)}
{hasMore && (
<li ref={sentinel} aria-hidden="true">
{busy ? "Loading..." : "Scroll for more"}
</li>
)}
</ul>
);
}The rootMargin of "200px" triggers loading when the sentinel is still 200 px below the viewport, so by the time the user actually reaches the bottom, the next batch is usually rendered. Tune it for your average load time.
Use stable keys
The most common bug in infinite-scroll lists is using the array index as the React key. When you append to the array, indices shift, React reuses the wrong DOM nodes, and rows visibly flicker on scroll. Use the resource id; it never changes. In v3 the id is a UUID string.
// BAD: the key is the array index, items shift on update
{items.map((u, i) => <li key={i}>{u.name}</li>)}
// GOOD: the key is the resource id, never changes
{items.map(u => <li key={u.id}>{u.name}</li>)}Accessibility
Infinite scroll is hard to use for keyboard users and screen readers. Two fixes:
- Always include a "Load more" button inside the sentinel for keyboard users. The observer triggers it on scroll; pressing Enter triggers it manually.
- Provide a way to pause. Long lists never reach the footer if loading is automatic. Either offer a "Pause loading" toggle, or switch to manual loading after N pages.
Restoring scroll position
If the user clicks an item, navigates away, and hits Back, they expect to return to the same scroll position with all loaded items still visible. Save the loaded items and scroll offset in sessionStorage on unmount; load them back on mount. React Router 6 handles some of this automatically with unstable_useScrollRestoration; check the version.
Combine with simulated latency
When testing infinite scroll, add a delay before each real request so you can see your loading indicator. With instant local responses you cannot tell whether the spinner ever shows. v3 has a separate path for this: GET /public/v3/http/delay/<ms> waits that many milliseconds and then answers.
await fetch("https://gorest.co.in/public/v3/http/delay/1500"); // wait 1.5 s
const res = await fetch(url);Put these two lines at the start of the try block in loadMore while you test, and remove them after.
Common mistakes
- Listening to scroll events instead. Scroll handlers fire dozens of times per second; you debounce; the user scrolls fast and misses a load. IntersectionObserver is the right tool.
- Forgetting hasMore. Without it, the observer keeps triggering after the last page, and you keep calling the API for nothing.
- Re-creating the observer on every render. Keep the effect dependencies tight (
[hasMore, items.length]) and disconnect on cleanup. - Mixing infinite scroll and pagination. Pick one. Users hate hybrid lists where you scroll for a while and then hit a "Page 2" button.
Keep building
Test loading skeletons with simulated latency
Use /http/delay/<ms> to make GoRest take seconds to respond, so you can verify your skeleton screens render without flicker.
Test 401, 422, 429 and 500 handlers
Force any status code with /http/status/<code> to make sure your error UI never shows blank screens or eats stack traces.
Build a paginated user list in React
A working component that fetches a page, renders rows, and uses the v3 cursor to render Previous/Next correctly.