use-pagination (use-pagination)
Hook for controlling list pagination.
v0.1.0
Usage
import { use-pagination } from "@/hooks"
1"use client";
2
3import React from "react";
4
5import { Button } from "@/components/ui/button";
6import {
7 Card,
8 CardContent,
9 CardDescription,
10 CardFooter,
11 CardHeader,
12 CardTitle,
13} from "@/components/ui/card";
14
15import { usePagination } from "@/components/hooks/use-pagination";
16
17export function UsePaginationDemo() {
18 const totalItems = 100;
19 const {
20 page,
21 pageSize,
22 totalPages,
23 setPage,
24 nextPage,
25 prevPage,
26 setPageSize,
27 } = usePagination(totalItems, { initialPage: 1, initialPageSize: 10 });
28
29 return (
30 <Card className="relative max-w-sm w-full">
31 <CardHeader>
32 <CardTitle>usePagination</CardTitle>
33 <CardDescription>
34 Example of pagination using the <code>usePagination</code> hook.
35 </CardDescription>
36 </CardHeader>
37
38 <CardContent>
39 <p>
40 Page: <strong>{page}</strong> of <strong>{totalPages}</strong>
41 </p>
42 <p>
43 Items per page: <strong>{pageSize}</strong>
44 </p>
45 </CardContent>
46
47 <CardFooter className="flex flex-wrap gap-2">
48 <Button onClick={() => setPageSize(5)}>5 / page</Button>
49 <Button onClick={() => setPageSize(10)}>10 / page</Button>
50 <Button onClick={() => setPageSize(20)}>20 / page</Button>
51 <Button onClick={prevPage} disabled={page <= 1}>
52 Previous
53 </Button>
54 <Button onClick={nextPage} disabled={page >= totalPages}>
55 Next
56 </Button>
57 </CardFooter>
58 </Card>
59 );
60}
61
Install
npx wkkkis-hooks add use-pagination
Options
Name | Type | Default | Description |
---|---|---|---|
totalItems | number | - | Total number of items to paginate |
initialPage | number | 1 | Initial page |
initialPageSize | number | 10 | Number of items per page |
Features
- Manages page and pageSize state.
- Automatically calculates the total number of pages.
- Ensures the current page stays within valid bounds.
- Supports dynamic changes to pageSize .
Files in this hook
Source | Destination |
---|---|
files/use-pagination.ts | src/hooks/use-pagination.ts |