usePagination.ts 654 B

12345678910111213141516171819
  1. import { useEffect, useState } from 'react';
  2. export function usePagination<T>(items: T[], initialPage: number, itemsPerPage: number) {
  3. const [page, setPage] = useState(initialPage);
  4. const numberOfPages = Math.ceil(items.length / itemsPerPage);
  5. const firstItemOnPageIndex = itemsPerPage * (page - 1);
  6. const pageItems = items.slice(firstItemOnPageIndex, firstItemOnPageIndex + itemsPerPage);
  7. const onPageChange = (newPage: number) => {
  8. setPage(newPage);
  9. };
  10. // Reset the current page when number of changes has been changed
  11. useEffect(() => setPage(1), [numberOfPages]);
  12. return { page, onPageChange, numberOfPages, pageItems };
  13. }