Design Converter
Education
Last updated on Feb 6, 2025
Last updated on Feb 5, 2025
In modern web development, handling large datasets efficiently is a constant challenge. For developers working with React, implementing server-side pagination is an effective way to manage large tables without overwhelming the client.
In this blog , we will explore React Table server-side pagination, its significance, and how to implement it with ease.
React Table is a powerful library designed to display and manipulate data in tabular form. It comes with built-in features like sorting, filtering, and pagination. While client-side pagination works well for small datasets, when dealing with large datasets, server-side pagination is often a more efficient approach.
React Table server-side pagination enables you to fetch only the data that is required for each page, reducing the load on the browser and improving performance. In this post, we will show you how to implement server-side pagination using React Table and also explore pagination logic and best practices.
Before jumping into the implementation, it's crucial to understand the difference between client-side pagination and server-side pagination.
For large datasets, server-side pagination is the preferred approach because it offloads the task of sorting and filtering to the server.
Let’s go through the implementation step by step. Below is a basic example of how to use React Table with server-side pagination.
You will need to install React Table and a backend API that supports server-side pagination. Here's how to install React Table:
1npm install react-table 2
In this case, we will use a React Query example to fetch data from a backend API.
1npm install react-query 2
Let's start by fetching the data from the server. Here's a basic setup to fetch data for server-side pagination using React Query:
1import React, { useEffect } from "react"; 2import { useQuery } from "react-query"; 3import { useTable, usePagination } from "react-table"; 4 5const fetchData = async (pageIndex, pageSize) => { 6 const response = await fetch(`/api/data?page=${pageIndex}&pageSize=${pageSize}`); 7 return response.json(); 8}; 9 10const Table = () => { 11 const { pageIndex, pageSize } = useTable({ 12 manualPagination: true, // manual pagination logic 13 pageCount: -1 // unknown number of pages until data is fetched 14 }); 15 16 const { data, isLoading } = useQuery( 17 ["data", pageIndex, pageSize], 18 () => fetchData(pageIndex, pageSize), 19 { 20 keepPreviousData: true, // Keep previous data while fetching new data 21 } 22 ); 23 24 // Table pagination UI 25 const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, state: { pageIndex } } = useTable({ 26 data: data?.rows || [], 27 columns, 28 manualPagination: true, 29 pageCount: data?.totalPages || 0 30 }); 31 32 return ( 33 <div> 34 <table {...getTableProps()}> 35 <thead> 36 {headerGroups.map(headerGroup => ( 37 <tr {...headerGroup.getHeaderGroupProps()}> 38 {headerGroup.headers.map(column => ( 39 <th {...column.getHeaderProps()}>{column.render("Header")}</th> 40 ))} 41 </tr> 42 ))} 43 </thead> 44 <tbody {...getTableBodyProps()}> 45 {rows.map(row => { 46 prepareRow(row); 47 return ( 48 <tr {...row.getRowProps()}> 49 {row.cells.map(cell => { 50 return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>; 51 })} 52 </tr> 53 ); 54 })} 55 </tbody> 56 </table> 57 {/* Pagination controls */} 58 <div> 59 <button 60 onClick={() => pageIndex > 0 && gotoPage(pageIndex - 1)} 61 disabled={pageIndex === 0} 62 > 63 Previous 64 </button> 65 <button 66 onClick={() => pageIndex < data?.totalPages - 1 && gotoPage(pageIndex + 1)} 67 disabled={pageIndex === data?.totalPages - 1} 68 > 69 Next 70 </button> 71 </div> 72 </div> 73 ); 74}; 75
On the server side, you need to handle pagination as well. Here’s a basic example of how the backend can handle server-side pagination:
app.get("/api/data", (req, res) => {
const { page = 0, pageSize = 10 } = req.query;
const data = fetchDataFromDatabase(); // Fetch data from database
const paginatedData = data.slice(page * pageSize, (page + 1) * pageSize);
res.json({
rows: paginatedData,
totalPages: Math.ceil(data.length / pageSize)
});
});
The pagination controls enable users to navigate between pages. By listening to page index changes, we can fetch the corresponding data from the backend.
1<button onClick={() => gotoPage(pageIndex - 1)} disabled={pageIndex === 0}> 2 Previous 3</button> 4<button onClick={() => gotoPage(pageIndex + 1)} disabled={pageIndex === totalPages - 1}> 5 Next 6</button> 7
The above code allows users to navigate through pages by changing the page index.
One of the significant advantages of React Table is its flexibility. You can customize the pagination controls and the pagination behavior to suit your project’s needs. You can implement your table pagination UI and customize pagination based on the pagination state.
React Table allows you to create expanded rows or sub-rows. If you need to display more data on the same page without fetching additional data from the server, you can use the parent row to hold extra information.
Implementing React Table server-side pagination is an excellent solution for managing large datasets. It ensures optimal performance by fetching only the data needed for each page. By combining React Query for data fetching and React Table for handling pagination, sorting, and filtering, you can create an efficient and highly customizable table component.
By understanding the server-side pagination logic and applying it properly, you can significantly improve the user experience and performance of your React applications.
If you want to take control of pagination and create your pagination UI, React Table gives you all the tools necessary. Start implementing server-side pagination today and make your tables more efficient!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.