React Pagination Hook
Drop-in typescript code to handle pagination properly with react hooks and URL query parameters
This short hook leverages several best practices:
- use an URL query parameter to persist the current state
- better UX when reloading the website
- better SEO since all pages are crawlable
- leverage
history.replace()
to preserve clean browser history - API surface is the same as
useState()
- graceful fallback to
1
if there is no page parameter set currently
import { useHistory, useLocation } from "react-router-dom";
export const usePagination = (): [number, (page: number) => void] => {
const { pathname, search } = useLocation();
const params = new URLSearchParams(search);
const page = parseInt(params.get('page') || "1");
const history = useHistory();
const setPage = (newPage = 1) => {
params.set('page', newPage.toString())
history.replace({ pathname, search: params.toString() });
}
return [page, setPage]
}