Pagination
Problem
Loading thousands of records at once overwhelms the browser, causing slow initial loads, high memory consumption, and sluggish rendering. Users rarely need to see all data at once, but fetching everything upfront wastes bandwidth and makes the application feel unresponsive. Large datasets need to be broken into manageable chunks.
Solution
Split large data sets into discrete pages users navigate through explicitly. This reduces initial load time and cognitive overhead compared to displaying everything at once.
Example
This example demonstrates a paginated list component that fetches data in discrete pages, loading 20 items at a time to avoid overwhelming the browser with large datasets.
// Framework-agnostic pagination
class PaginatedList extends HTMLElement {
constructor() {
super();
// Track current page number
this.page = 1;
this.data = null;
}
async connectedCallback() {
// Fetch first page when component connects
await this.fetchData();
this.render();
}
async fetchData() {
// Request specific page with limit on items
const response = await fetch(`/api/items?page=${this.page}&limit=20`);
this.data = await response.json();
}
async nextPage() {
// Increment page and fetch next set
this.page++;
await this.fetchData();
this.render();
}
render() {
const items = this.data?.items.map(item => `<li>${item.name}</li>`).join('');
this.innerHTML = `
<ul>${items}</ul>
<button id="next-btn">Next</button>
`;
// Wire up next button to fetch next page
this.querySelector('#next-btn').onclick = () => this.nextPage();
}
}
Benefits
- Reduces initial load time by fetching only the data needed for the current page.
- Decreases memory consumption by not loading thousands of records at once.
- Makes large datasets manageable with clear navigation controls.
- Improves perceived performance by showing results faster.
Tradeoffs
- Requires explicit user action to view more content, interrupting flow.
- Can be frustrating when users need to search across multiple pages.
- Adds complexity with page state management and navigation logic.
- Makes it harder to perform operations like search or sort across all data.