npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-pagination

v2.0.1

Published

A React hook to help manage pagination state

Downloads

23,767

Readme

✨ Features

  • 🛠 State-only hook & callbacks, you provide your own UI controls
  • 📦 Compatible with any pagination method like GraphQL Relay Cursor, OData, etc.
  • ⚡️ Works with both server side and client side pagination
  • 🐜 Simple and lightweight — less than 2KB gzipped

Example

import { usePagination } from "react-use-pagination";

function App() {
    const [data] = React.useState([]); // <- your data

    const {
        currentPage,
        totalPages,
        setNextPage,
        setPreviousPage,
        nextEnabled,
        previousEnabled,
        startIndex,
        endIndex,
    } = usePagination({ totalItems: data.length });

    return (
        <div>
            <MyDataTable data={data.slice(startIndex, endIndex)} />

            <button onClick={setPreviousPage} disabled={!previousEnabled}>
                Previous Page
            </button>
            <span>
                Current Page: {currentPage} of {totalPages}
            </span>
            <button onClick={setNextPage} disabled={!nextEnabled}>
                Next Page
            </button>
        </div>
    );
}

API

const paginationState = usePagination(options);

options

type Options = {
    totalItems: number;
    initialPage?: number; // (default: 0)
    initialPageSize?: number; // (default: 0)
};

paginationState

type PaginationState = {
    // The current page
    currentPage: number;

    // The first index of the page window
    startIndex: number;

    // The last index of the page window
    endIndex: number;

    // Whether the next button should be enabled
    nextEnabled: number;

    // Whether the previous button should be enabled
    previousEnabled: number;

    // The total page size
    pageSize: number;

    // Jump directly to a page
    setPage: (page: number) => void;

    // Jump to the next page
    setNextPage: () => void;

    // Jump to the previous page
    setPreviousPage: () => void;

    // Set the page size
    setPageSize: (pageSize: number, nextPage?: number = 0) => void;
};

Client Side Pagination

startIndex and endIndex can be used to implement client-side pagination. The simplest possible usage is to pass these properties directly to Array.slice:

const [data] = React.useState(["apple", "banana", "cherry"]);
const { startIndex, endIndex } = usePagination({ totalItems: data.length, initialPageSize: 1 });

return (
    <ul>
        {data.slice(startIndex, endIndex).map((item) => (
            <li>{item}</li>
        ))}
    </ul>
);

Server Side Pagination

startIndex and pageSize can be used to implement a standard limit/offset (also known as top/skip) type of pagination:

// Keep track of length separately from data, since data fetcher depends on pagination state
const [length, setLength] = React.useState(0);

// Pagination hook
const { startIndex, pageSize } = usePagination({ totalItems: length, initialPageSize: 1 });

// Fetch Data
const [_, data] = usePromise(
    React.useCallback(
        () => fetchUsers({ offset: startIndex, limit: pageSize }),
        [startIndex, pageSize]
    )
);

// When data changes, update length
React.useEffect(() => {
    setLength(data.length);
}, [data]);

return (
    <ul>
        {data.slice(startIndex, endIndex).map((item) => (
            <li>{item}</li>
        ))}
    </ul>
);