Machine Coding · Lesson 7 of 12 · 4 min
Pagination & Infinite Scroll
This is a classic machine coding problem. Your solution reveals how you handle state, async operations, and user experience under pressure.
When you need to display a list of thousands of items, you can't just fetch and render them all. The network call will be slow, and the browser will choke on the DOM size. The solution is to load data in chunks. There are two primary patterns for this: pagination and infinite scroll. You need to know how to implement both and, more importantly, how to choose between them.
Know the Trade-offs: Pagination vs. Infinite Scroll
Pagination breaks content into discrete pages. It's predictable and gives the user a sense of scope and control. Use it when the user has a specific goal, like finding an item on page 3 of search results or navigating a product catalog.
Infinite scroll loads content continuously as the user scrolls. It's good for exploration and discovery, where the goal is to keep the user engaged. Think social media feeds or image galleries.
Here's the breakdown:
| Aspect | Pagination | Infinite Scroll | |---|---|---| | User Goal | Finding a specific item | Browsing, discovery | | Control | High (jump to any page) | Low (linear only) | | Context | Clear (Page 5 of 20) | Vague (no sense of total size) | | Performance | Predictable DOM size | Can create a massive DOM, leading to lag | | Footer Access | Easy | Can be impossible to reach | | Mobile UX | Fiddly buttons | Natural, swipe-based |
"When would you use pagination for a mobile app?" This question tests if you can think beyond defaults. While infinite scroll is common on mobile, pagination is better for e-commerce check-out histories or bank transaction lists. The user isn't "discovering" their past purchases; they're looking for a specific one and need clear, bounded navigation.
The Two Types of Pagination: Offset vs. Cursor
How you ask the server for the "next" chunk of data matters.
Offset-based pagination is the most common. The client requests GET /items?page=2&limit=20. It's simple to implement on both ends.
The trap: This approach is not stable if the underlying data changes frequently. If a new item is added to the beginning of the list while you're on page 2, every subsequent page will be off by one. You'll see a duplicate of the last item from page 2 when you load page 3.
Cursor-based pagination is more robust. The client requests GET /items?after=itemID_of_last_item&limit=20. The "cursor" is an opaque, stable identifier for the last item you saw. This way, you always get the next 20 items after that specific one, regardless of how many new items were added elsewhere. Use this for real-time feeds or frequently updated lists.
How to Build Infinite Scroll with IntersectionObserver
The modern way to implement infinite scroll is with the IntersectionObserver API. It's far more performant than listening to scroll events. The observer watches a "sentinel" element at the bottom of your list and fires a callback only when it enters the viewport.
This diagram shows the core logic loop:
Here is a standard implementation in React. It manages loading states, appends new data, and cleans up the observer.
import React, { useState, useEffect, useRef, useCallback } from 'react';
interface Item {
id: number;
name: string;
}
// Simulate an API call that returns the next chunk of data
async function fetchItems(offset: number, limit: number): Promise<{ data: Item[]; hasMore: boolean }> {
const allItems: Item[] = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}` }));
await new Promise(resolve => setTimeout(resolve, 500)); // Network delay
const data = allItems.slice(offset, offset + limit);
const hasMore = (offset + limit) < allItems.length;
return { data, hasMore };
}
export function InfiniteScrollList() {
const [items, setItems] = useState<Item[]>([]);
const [offset, setOffset] = useState(0);
const [hasMore, setHasMore] = useState(true);
const [loading, setLoading] = useState(false);
const sentinelRef = useRef<HTMLDivElement>(null);
const loadMore = useCallback(async () => {
if (loading || !hasMore) return;
setLoading(true);
const { data: newItems, hasMore: newHasMore } = await fetchItems(offset, 10);
setItems(prev => [...prev, ...newItems]);
setHasMore(newHasMore);
setOffset(prev => prev + 10);
setLoading(false);
}, [loading, hasMore, offset]);
useEffect(() => {
const observer = new IntersectionObserver(entries => {
if (entries[0].isIntersecting) {
loadMore();
}
});
const sentinel = sentinelRef.current;
if (sentinel) {
observer.observe(sentinel);
}
return () => {
if (sentinel) {
observer.unobserve(sentinel);
}
};
}, [loadMore]);
return (
<div>
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
<div ref={sentinelRef} />
{loading && <p>Loading...</p>}
{!hasMore && <p>You've reached the end.</p>}
</div>
);
}
The trap: Forgetting to clean up the observer in the useEffect return function. This is a memory leak and an instant red flag in an interview. Also, notice the check if (loading || !hasMore) return;. Without it, the observer could trigger multiple fetches for the same data while the first one is still in flight.
The Performance Trap of a Long List
Infinite scroll solves the data fetching problem, but not the data rendering problem. As the user scrolls, the number of DOM nodes grows. A list with 5,000 items, each with a few nodes, can easily create 15,000+ total nodes.
This bloats memory and makes any style recalculation or repaint expensive. The UI will start to feel sluggish because the browser can't update the screen within its 16ms per frame budget.
The solution is "virtualization" or "windowing," where you only render the items currently visible in the viewport (plus a small buffer). This keeps the DOM small and performance high, no matter how long the list is.
Try it
Refactor the infinite scroll component to work with a "Load More" button instead of IntersectionObserver. When the button is clicked, it should fetch the next page. This is a common accessible alternative to automatic loading.
Next: We'll solve the performance trap of long lists in "Advanced UI Components: Modals & Tooltips".
Lock it in — apply this lesson under interview conditions.