Effortless Pagination with the usePagination React Hook
- #Tips & Tricks
Pagination is an essential feature for blogs and content-heavy websites, allowing users to navigate through posts or items efficiently without overwhelming them. In the SanityPress starter template, a single-file custom React hook was built specifically to handle this functionality for the new Blog Frontpage module.
This custom hook generates a paginated list of items when passed specific options. The hook is flexible, allowing for control over the number of items displayed per page, and it can be easily paired with a customizable <Pagination>
component for a seamless user experience.
Why Build a Custom Pagination Hook?π
The idea behind this hook is to offer a simple, lightweight solution to pagination without relying on third-party libraries. It allows developers to:
- Paginate items dynamically based on the current page.
- Control how many items appear per page.
- Integrate a fully customizable pagination UI.
The custom hook is actively used within the SanityPress project and can be easily implemented in other React/Next.js projects requiring a paginated display of items, such as blog posts or product listings.
How to Add Pagination to Your Projectπ
If you want to integrate this pagination hook into your own project, itβs easy to get started. Hereβs a quick guide:
1. Copy and paste the codeπ
You can copy and paste the code directly from the SanityPress GitHub repository and integrate it into your project.
2. Use the hook and pass optionsπ
Here's a basic implementation of the hook and the <Pagination>
component:
export default function MyComponent({ itemsToPaginate }) {
const { paginatedItems, Pagination } = usePagination({
items: itemsToPaginate, // your items
itemsPerPage: 6,
})
return (
<div>
<ul>
{paginatedItems.map(...)}
</ul>
<Pagination className="..." />
</div>
)
}
The <Pagination>
component can be styled and customized according to your needs. You can also build one from scratch by retrieving additional properties from the destructured object, giving you complete control over the UI.
Find all options and available properties in the source code here.
Use in SanityPress, or use anywhere!π
In SanityPress, this hook powers the new Blog Frontpage module, where paginated blog posts are fetched from Sanity CMS and displayed to users. It's designed to be easily adaptable to various use cases beyond blogging, providing developers with the flexibility they need.
By leveraging this hook, you can enhance user experience, improve performance by loading only necessary content, and maintain a clean, easy-to-navigate interface. For a deeper look and to add this feature to your project, head over to the GitHub repo and use usePagination
and <Pagination>
!