We often work with web applications that need to fetch large amounts of data from a server through APIs and render it on the screen.
For example, in a Social media application we fetch and render users’ posts and comments. In an HR dashboard we display information about candidates who applied for a job. And in an Email Client we show the a user’s emails.
Rendering all the data at once on the screen can cause your webpage to slow down considerably because of the large number of DOM elements present in the webpage.
If we want to optimize on performance we can adopt various techniques to render data in a more efficient manner. Some of these methods include infinite scroll with virtualization and pagination.
Pagination works well when you know the size of the data in advance, and you don’t make frequent additions or deletions to the data-set.
For instance in a social media website where new posts are published every few milliseconds, pagination wouldn’t be an ideal solution. But it would work well for an HR dashboard where candidate applications are displayed and need to be filtered or sorted as well.
In this post, we will focus on pagination and we’ll build a custom controlled component that handles page buttons based on the current page and total data count.
We will also write a custom React hook that gives us a range of numbers to be rendered by the pagination component. We can use this hook independently as well when we want to render a pagination component with different styles or in a different design.
Below is a demo of what we will be building in this tutorial:
How to Set Up the Project
If you are familiar with setting up a React project, you can skip this section.
In order to set up our React Project, we will use the command line package. You can install the package globally using
npm install -g create-react-app or
yarn add global create-react-app.
create-react-app from the command line to create a new project like this:
Next we need to install our dependencies. We will just be using a simple additional dependency called
classnames which provides flexibility when handling multiple classNames conditionally.
To install it run
npm install classnames or
yarn add classnames .
Now, we can run our project using the below command:
How to Define the Interface
Now that we have our project running, we’ll dive straight into our
Let’s first look at what values we need as props to our
From the pagination component we’ll invoke the
usePagination hook which will take in the following parameters to compute the page ranges:
How to Implement the usePagination Hook
Below are the few things we need to keep in mind while implementing the
Keeping the above things in mind let’s create a file called
usePagination.js in our project
src folder and start with the implementation.
Our code skeleton will be as follows:
If we look at the above code, we are using the
useMemo hook to compute our core logic. The
useMemo callback will run when any value in its dependency array changes.
Also we are setting the
defaultValue of our
siblingCount prop to be
1 as it is an optional prop.
Before we go ahead and implement the code logic, let’s understand the different behaviors of the
Pagination component. The below image contains the possible states of a pagination component:
Note that there are four possible states for a pagination component. We’ll go over them one by one.
As a first step, we shall go about calculating the total pages from
pageSize as follows:
Notice that we are using
Math.ceil to round of the number to the next higher integer value. This ensures that we are reserving an extra page for the remaining data.
Next, we’ll go ahead and implement a custom
range function which takes in a
end value and returns an array with elements from start to end:
Finally, we’ll implement the core logic by keeping the above cases in mind.
The idea of the implementation is that we identify the range of numbers we want to show in our pagination component and then join them together with the separators or DOTS when we return the final range.
For the first scenario where our
totalPageCount is less than the total number of pills we calculated based on the other params, we just return a range of numbers
For the other scenarios, we go about identifying whether we need DOTS on the left or right side of the
currentPage by calculating the left and right indices after including the sibling pills to the
currentPage and then make our decisions.
Once we know where we want to show the DOTS, the rest of the calculations are quite straightforward.
How to Implement the Pagination Component
As I mentioned earlier, we’ll be using the
usePagination hook in our pagination component and we’ll map over the returned range to render them.
We create a
Pagination.js file in our
src folder and implement the code logic as follows:
We do not render a
Pagination component if there are fewer than two pages (and then we return
We render the
Pagination component as a list with left and right arrows which handle the previous and next actions the user makes. In between the arrows, we map over the
paginationRange and render the page numbers as
pagination-items. If the page item is a DOT we render a unicode character for it.
As a special handling we add a
disabled class to the left/right arrow if the
currentPage is the first or the last page, respectively. We disable the
pointer-events and update the styles of the arrow icons through CSS if the icon needs to be disabled.
We also add click event handlers to the page pills which will invoke the
onPageChanged callback function with the updated value of
Our CSS file will contain the following styles:
And that’s it!
Our generic pagination implementation is ready and we can use it anywhere in our codebase.
How to Use the Custom Pagination Component
As a last step, let’s incorporate this component in a small example.
For the scope of this article, we shall render static data in the form of a table. So let’s go ahead and do that first:
At this point our UI looks as follows:
Now to incorporate the
Pagination component, we need two things.
For the purposes of this demo, we’ll keep the
PageSize constant and set its value to
10 we can also provide a selector for the user to select the desired
Once we have made changes, we can go ahead and render our
Pagination component with the appropriate props.
With these changes in mind, our final code will be as follows:
Here is a live demo of this tutorial:
In this article, we create a custom React hook
usePagination and used it within our
Pagination component. We also implemented a short demo which used this component.
You can check out the full source code for this tutorial in this GitHub repository.
If you have any questions or suggestions regarding this article, please feel free to reach out to me on Twitter.
Thank you for reading.