Docs
usePagination

Manage pagination state and logic with the usePagination hook, providing methods to navigate through pages and track current page state

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-pagination

Usage

"use client"
 
import { usePagination } from "@/hooks/use-pagination"
 
export function Component() {
  const {
    currentPage,
    totalPages,
    nextPage,
    prevPage,
    goToPage,
    startIndex,
    endIndex,
    pageNumbers,
    canPreviousPage,
    canNextPage,
    hasPreviousEllipsis,
    hasNextEllipsis,
  } = usePagination({
    totalItems: 100, // Total number of items to paginate
    itemsPerPage: 10, // Number of items per page
    maxVisiblePages: 5, // Maximum number of visible page numbers
    resetOnTotalItemsChange: true, // Reset pagination when total items change
    initialPage: 1, // Initial page number to start from
  })
 
  return (
    <div style={{ padding: "20px", maxWidth: "600px", margin: "0 auto" }}>
      <p>Current Page: {currentPage}</p>
      <p>Total Pages: {totalPages}</p>
      <p>
        Items {startIndex + 1} - {endIndex + 1} of {totalItems}
      </p>
      <div>
        <button onClick={prevPage} disabled={!canPreviousPage}>
          Previous
        </button>
        {hasPreviousEllipsis && <span>...</span>}
        {pageNumbers.map((page) => (
          <button
            key={page}
            onClick={() => goToPage(page)}
            disabled={currentPage === page}
          >
            {page}
          </button>
        ))}
        {hasNextEllipsis && <span>...</span>}
        <button onClick={nextPage} disabled={!canNextPage}>
          Next
        </button>
      </div>
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
totalItemsnumberTotal number of items to paginate.0No
itemsPerPagenumberNumber of items per page.10No
initialPagenumberInitial page number to start from.1Yes
pageNumbersnumber[]Array of page numbers to display in pagination.[]Yes
canPreviousPagebooleanWhether to allow navigation to the previous page.trueYes
canNextPagebooleanWhether to allow navigation to the next page.trueYes
hasPreviousEllipsisbooleanWhether to show an ellipsis for previous pages.falseYes
hasNextEllipsisbooleanWhether to show an ellipsis for next pages.falseYes

Return Values

NameTypeDescription
currentPagenumberThe current page number.
totalPagesnumberThe total number of pages based on the item count and page size.
nextPage() => voidFunction to navigate to the next page.
prevPage() => voidFunction to navigate to the previous page.
goToPage(page: number) => voidFunction to navigate to a specific page.
startIndexnumberThe index of the first item on the current page.
endIndexnumberThe index of the last item on the current page.