Pagination for Beginners – Frontend Interview Question
What is Pagination?
Pagination is like turning the pages of a book. You see a limited number of items on each page; if there are more items, you can go to the next page to see them.
In web applications, pagination refers to the practice of dividing a large set of data into smaller, more manageable chunks, often to improve system performance and user experience. Instead of retrieving and displaying the entire dataset at once, the data is fetched and presented in smaller portions or “pages.”
Why pagination?
Pagination enhances website performance by loading smaller portions of data at a time, resulting in quicker page loading and a smoother browsing experience. It provides control over attributes.
When pagination is employed, the API (an interface that allows different software applications to communicate with each other) can restrict the quantity of data stored in memory at any instance. This limitation proves beneficial by enhancing the overall user experience through a more rapid and responsive interface.
Breaking down data into smaller subsets during pagination diminishes the demands on memory, processing capacity, and bandwidth on both the server (where the website is hosted) and the client side (the user’s device). This approach is a strategic way to efficiently manage resources in web interactions.
Pagination Implementation in Frontend
Here, we are going to talk about two ways of pagination implementation in frontend, client-side pagination and server-side pagination.
Client-side pagination
Client-side pagination is a technique for managing and displaying large datasets on a web page without consistently requesting data from the server. Instead of sending multiple smaller requests for specific page subsets, all the data is fetched at once, and the browser handles sorting and displaying it in manageable chunks. Here is a basic react component:
import { useState } from "react";
function PaginationComponent() {
const pagesize = 5;
const [currentPage, setCurrentPage] = useState(1);
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("https://api.example.com/data");
const fetchedData = await response.json();
setData(fetchedData);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
const pages = Math.ceil(data.length / pagesize);
const end = currentPage * pagesize;
const start = end - pagesize;
const value = data.slice(start, end);
const changePageNumber = (pageNum) => {
setCurrentPage(pageNum);
};
return (
<div>
<div className="App">
{value?.map((item, index) => {
return <h1>{item.name}</h1>;
})}
</div>
<div>
{[...Array(pages)].map((_, index) => (
<button onClick={() => changePageNumber(index + 1)}>
{index + 1}
</button>
))}
</div>
</div>
);
}
export default PaginationComponent;
How does client-side pagination work:
- Initial Download: The server sends the entire dataset to the client (user’s browser) in a single response.
- Data Processing: The browser stores the data locally and uses JavaScript to filter, sort, and divide it into “virtual pages” based on a chosen page size (e.g., 5 items per page).
- Page Display: Only the data for the currently displayed page is rendered in the user interface.
- Navigation: As users click between pages, the browser manipulates the locally stored data to display the requested page without making additional server requests.
Benefits of client-side pagination:
- Faster perceived performance: Navigating between pages feels instant as data is already available.
- Reduced server load: The server only needs to process one request for the entire dataset.
- Offline support: Users can access previously viewed pages without an internet connection.
- Flexibility and customization: More control over presentation and interaction with the data.
Drawbacks of client-side pagination:
- Initial load penalty: Downloading a large dataset initially can be slower.
- Limited to smaller datasets: Managing a massive amount of data locally can be memory-intensive.
- Less secure: Sensitive data might be exposed locally if not handled carefully.
- Limited sorting and filtering options: Complex logic might be challenging to implement efficiently on the client side.
When to use client-side pagination:
Small to medium datasets (e.g., product listings, blog posts)
When user experience and responsiveness are crucial offline functionality is a must-have.
Server-side pagination
Server-side pagination differs from client-side pagination by offloading the heavy lifting of managing large datasets to the server. Instead of sending the entire dataset to the client simultaneously, the server handles filtering, sorting, and retrieving only the specific data needed for each requested page.
import React, { useState, useEffect } from 'react';
const PaginationComponent= () => {
const [items, setItems] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
useEffect(() => {
const fetchItems = async () => {
try {
const pageSize = 5; // Adjust this based on your API or
application requirements
const response = await fetch(`/api/items?page=${currentPage}&pageSize=${pageSize}`);
const data = await response.json();
setItems(data.items);
setTotalPages(data.totalPages);
} catch (error) {
console.error('Error fetching items:', error);
}
};
fetchItems();
}, [currentPage]);
const changePageNumber= (pageNum) => {
setCurrentPage(pageNum);
};
return (
<div>
<h2>Item List</h2>
{/* Display your items here */}
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
{/* Pagination */}
<div>
{Array.from({ length: totalPages }, (_, index) => (
<button key={index + 1} onClick={() => changePageNumber(index + 1)}>
{index + 1}
</button>
))}
</div>
</div>
);
};
export default PaginationComponent;
How server-side pagination works:
- Client Request: The client sends a request to the server, specifying the page number and the number of items per page (pagination parameters).
- Server Processing: The server receives the request and processes it by fetching only the necessary subset of data from the database based on the pagination parameters.
- Data Sent to Client: The server then sends only the required data (e.g., a specific page of records) back to the client.
- Display on Client: The client-side application displays the received data, and the user can navigate through different pages using the pagination controls.
Benefits of server-side pagination:
- Efficient Resource Management: The server sends only the necessary data for the current page, reducing the load on both the server and the client.
- Suitable for Large Datasets: Works well with massive amounts of data without causing performance issues on the client side.
- Secure: Sensitive data remains on the server, reducing the risk of exposure.
Drawbacks of server-side pagination:
- Slower Perceived Performance: Loading new pages requires server requests, leading to a slightly slower user experience.
- Dependent on Server Response: Pagination relies on the server to provide the correct subset of data.
When to use server-side pagination:
Large datasets where client-side handling might be impractical.
When security concerns dictate that sensitive data should remain on the server.
In scenarios where initial load time is less critical compared to ongoing performance.
Conclusion:
Choosing between client-side and server-side pagination in a web application depends on the specific requirements of your application. Consider factors such as dataset size, user experience expectations, and the trade-offs between initial load time and ongoing performance. A well-informed decision will contribute to a responsive, efficient, and secure web application.