Skip to content

Commit

Permalink
(fix) Memoize the returned callback functions from usePagination (#741)
Browse files Browse the repository at this point in the history
  • Loading branch information
vasharma05 authored Aug 1, 2023
1 parent e1757ad commit 28efded
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 23 deletions.
6 changes: 3 additions & 3 deletions packages/framework/esm-framework/docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -4330,14 +4330,14 @@ ___
| Name | Type |
| :------ | :------ |
| `currentPage` | `number` |
| `goTo` | (`page`: `number`) => `void` |
| `goToNext` | () => `void` |
| `goToPrevious` | () => `void` |
| `paginated` | `boolean` |
| `results` | `T`[] |
| `showNextButton` | `boolean` |
| `showPreviousButton` | `boolean` |
| `totalPages` | `number` |
| `goTo` | (`page`: `number`) => `void` |
| `goToNext` | () => `void` |
| `goToPrevious` | () => `void` |

#### Defined in

Expand Down
62 changes: 42 additions & 20 deletions packages/framework/esm-react-utils/src/usePagination.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** @module @category UI */
import { useMemo, useState } from "react";
import { useCallback, useMemo, useState } from "react";

const defaultResultsPerPage = 10;

Expand All @@ -22,25 +22,47 @@ export function usePagination<T>(
return data.slice(lowerBound, upperBound);
}, [data, page, resultsPerPage]);

return {
results,
totalPages,
currentPage: page,
paginated: data.length > resultsPerPage,
showNextButton: page < totalPages,
showPreviousButton: page > 1,
goTo(page: number) {
const goTo = useCallback(
(page: number) => {
setPage(Math.max(1, Math.min(totalPages, page)));
},
goToNext() {
if (page < totalPages) {
setPage(page + 1);
}
},
goToPrevious() {
if (page > 1) {
setPage(page - 1);
}
},
};
[setPage, totalPages]
);
const goToNext = useCallback(() => {
if (page < totalPages) {
setPage(page + 1);
}
}, [page, totalPages, setPage]);

const goToPrevious = useCallback(() => {
if (page > 1) {
setPage(page - 1);
}
}, [page, setPage]);

const memoisedPaginatedData = useMemo(
() => ({
results,
totalPages,
currentPage: page,
paginated: data.length > resultsPerPage,
showNextButton: page < totalPages,
showPreviousButton: page > 1,
goTo,
goToNext,
goToPrevious,
}),
[
results,
totalPages,
data.length,
resultsPerPage,
page,
goTo,
goToNext,
goToPrevious,
]
);

return memoisedPaginatedData;
}

0 comments on commit 28efded

Please sign in to comment.