Pagination, both server-side and client-side

Dharshan
2 min readMay 2, 2022

In this guide, we will create a paginated table using Next.js, React Query with TypeScript and Tailwind CSS. Let's dive deep in.

Setup

  1. Create a Next.js app using the create-next-app with TypeScript template by running the following command:
npx create-next-app@latest --typescript

2. Install the dependencies

npm i react-query axios mongoose react-icons

3. Setup Tailwind

npm install -D tailwindcss postcss autoprefixernpx tailwindcss init -p

Add the following to your tailwind.config.js

module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

And this to your global.css

@tailwind base;
@tailwind components;
@tailwind utilities;

Markup

Let's write down some markup to render a table with static content and style them using Tailwind classes.

Mongoose models

Now let’s move on by creating a mongoose schema and model to represent ‘user’ entity.

Build the API

We will use the api folder created by the create-next-app to write the server-side logic.

We will use thelimit(), skip() and count() methods from mongoose to achieve pagination. Read more about them in doc

React Query with useState()

Now for the UI logic, we will use the useQuery() from React Query with the useState() hook.

Conclusion

To achieve pagination on both server-side and client-side using Next.js and React Query with Typescript, we started with static markup. We continued to create mongoose model and API. Later, we refracted the code to use the real data that we fetched using the useQuery(). The important methods are limit(), skip() and count() in case of backend and keepPreviousData inside the useQuery() config object.

--

--

Dharshan

I am a full stack aspirant who enjoy building beautiful products. Solving problems through code to make life better is my motto.