API Reference
usePagination

usePagination

This hook provides functionality for managing the state of a paginated list. It enables tracking the current page, adjusting the number of items displayed per page, and ensuring that pagination remains within bounds based on the total number of items.

Usage

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import usePagination into your component.

import { usePagination } from '@ridgehkr/useful'

Example

Pagination.tsx
import usePagination, {
  PaginationOptions,
  PaginationState,
} from '@ridgehkr/useful'
 
function Pagination() {
  // total number of items to paginate
  const totalItems = 100
 
  // options for configuring pagination behavior
  const paginationOptions: PaginationOptions = {
    initialPage: 1,
    initialItemsPerPage: 10,
  }
 
  // retrieve pagination state and functions
  const {
    currentPage,
    itemsPerPage,
    setPage,
    setItemsPerPage,
  }: PaginationState = usePagination(totalItems, paginationOptions)
 
  return (
    <div>
      {/* Your paginated content */}
 
      <p>Pagination Example</p>
 
      <div>
        <button onClick={() => setPage(currentPage - 1)}>Previous</button>
        <span>
          Page {currentPage} of {Math.ceil(totalItems / itemsPerPage)}
        </span>
        <button onClick={() => setPage(currentPage + 1)}>Next</button>
        <select
          value={itemsPerPage}
          onChange={(e) => setItemsPerPage(Number(e.target.value))}
        >
          <option value={5}>5 per page</option>
          <option value={10}>10 per page</option>
          <option value={20}>20 per page</option>
        </select>
      </div>
    </div>
  )
}

API Reference

Hook Signature

usePagination(
  totalItems: number,
  options?: PaginationOptions
): PaginationState

Parameters

usePagination accepts two parameters:

PropertyTypeDescription
totalItemsnumberThe total number of items to paginate
optionsPaginationOptionsConfiguration options (see PaginationOptions table for details)

PaginationOptions

PropertyTypeDescription
initialPagenumberThe initial pagination page
initialItemsPerPagenumberThe initial number of items to display per page

Return Value

The hook returns a PaginationState object with the following properties:

PropertyTypeDescription
currentPagenumberThe current page of paginated items
itemsPerPagenumberThe number of items to display per page
setPage(page: number): voidFunction to set the current page
setItemsPerPage(perPage: number): voidFunction to set the number of items displayed per page