Pagination with ?page=
Medium · Search Params
Keep the current page in the URL (?page=2) instead of in useState: the page survives a reload, can be shared, and the Back button works.
useSearchParams() returns the current query as a **read-only** URLSearchParams. To build a new query, copy it first: new URLSearchParams(searchParams). Then render <Link>s to the new URLs.
There are 23 posts and 5 per page, so 5 pages. Update the component:
- Read the page from ?page=. A missing or non-whole value means page 1. Clamp it to 1..totalPages (?page=99 shows page 5).
- Show the posts of that page as <li> items and the text Page <n> of <total> in the <p>.
- Render a Prev link (hidden on page 1) and a Next link (hidden on the last page).
- Link hrefs keep all other search params and only change page. The link to page 1 **removes** page for a clean URL: from /?tag=js&page=2, Prev goes to /?tag=js. Use usePathname() to build the href (pathname + "?" + query, or just pathname when the query is empty).
Next: Tabs Synced with the URL