Urgent.News

What's breaking now, across thousands of outlets.

World

Filtering, and Pagination in Next.js 15 The Pattern I Actually Use

Every dashboard eventually needs the same three things. A search box, a few filters, and pagination once the list gets long. The version I used to build kept all of that in useState , which meant losing your filters the moment you refreshed the page or shared a link with someone else. Keeping this state in the URL instead fixed both problems at once. Here is the setup. 1. Why URL Search Params,…

Every dashboard eventually requires three essential components: a search box, filters, and pagination as the list grows in length. Previously, I implemented this structure using the useState hook, which presented two significant drawbacks. Firstly, any changes to the state would be lost upon page refresh or when sharing a link with others.

Secondly, the state could not be bookmarked or shared via URL, making it impossible for users to access a consistent view. To address these issues, I decided to store all these elements in the URL instead. This approach guarantees that a page refresh maintains the current state, shared links display the identical filtered results, and the browser's back button functions as anticipated.

The solution hinges on utilizing URL search parameters rather than useState state. A URL like /dashboard/orders?search=invoice&status=pending&page=2 encapsulates the entire current view, eliminating the need for client-side state reconstruction.

Next.js's Server Component architecture is employed to fetch and render the data in response to the current URL. In the OrdersPage component, the searchParams prop is utilized to obtain the search query, status, and page number from the URL. The currentPage variable is assigned the page number from the URL or defaulted to 1 if not found.

The getOrders function is then called with the search, status, and currentPage parameters to retrieve the relevant orders. The retrieved orders, the total number of pages, and the current page number are then returned to render the appropriate UI components.

Simultaneously, the OrderFilters component, which is a Client Component, updates the URL whenever the user interacts with the filter inputs. It utilizes useRouter, useSearchParams, and usePathname hooks to access the router, search parameters, and current pathname. The OrderFilters component updates the searchParams in response to user input, and the OrdersPage component listens for these changes to update the displayed data accordingly.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in World

More from Friday 7 August →