I’ve got a small problem:
Context:
I have a a react page that contains, one component with two sub-components, the first sub-component contains the filters, and the second sub-component contains links for the same page(just a different title), so when I click on one link I get redirected to the same main component, just with different route, as shown below:
This is my design:
Since all the links point to the same main component, on the server side(using Next.js), I used generateStaticParams
to dynamically generate all those pages.
Problem:
When I click on one of the links(Link component), I want to keep the same filter values(Filters component). So I want to keep the same state as the previous page by going to the new page with a different route.
The problem is that every time I click on one of the links, the new page is generated from the server side and I lose all the client data.
I’m looking for a good approach to solve this by not using localStorage
. And I don’t want to pass the data as query parameters using <Link>
from Next.
I thought also of using the Context
, but it’s available just on the client side and the data will be lost after changing the route.
Is there a way to solve this, even by changing the current design?
I’m using React 19 and Next.js 15, any help will be very appreciated.
2
Answers
generateStaticParams
is executed at build time to pre-generatestatic pages
for dynamic routes. It does not have access toruntime data
like cookies or request-based data. Instead you can make your new page (where you want to access updated/current filter values) server side and accesscookies()
API from thenext/headers
. This API is available in theApp Router Next.js 15
and allows you to read cookies directly on theserver-side
, ensuring that the data is available when the page is rendered. what you have to do is:1- Set cookies on the client-side when the user selects or updates a filter.
2- Access
cookies
in yourServer Component
, you can access the cookies usingnext/headers
.Server-Side Page:
If the state needs to persist across multiple pages and rehydration isn’t required (state doesn’t need to be saved server-side), you can use a React Context or a state management library like Zustand.
Context Example:
Try the below code once: