How to use useContext on a product page that is a server component
Unanswered
Lionhead posted this in #help-forum
LionheadOP
I have a product page on which the title and list of product cards are rendered, I tried to make the entire page and all cards completely server-side components, now the customer wanted to make buttons on top that will switch the display of cards either as a list of one in a row, or as a grid of 3 cards in a row . I used a context, made a provider, wrapped the application in a provider, and now I need to call the useChangeTypeGrid hook directly on the page, but for this I need to mark my page with the "use client" directive, which makes the entire product page and all the cards on it client components! it is not clear then why I tried to make everything server-side, how can it be done to save the server-side components?
13 Replies
Sun bear
If I get you correctly you are trying to create functionality that switches from grid view to row?
You unfortunatly cannot use context for this if you want cards to be server side, but you can use the url instead for state mangement for something like this.
For example if you have 2 views lets say "grid" and "row" you can create a button that changes the url to be http://example.com/products?view=grid
and based on that use searchParams to render the view
if (searchParams.view === "grid") return <GridView /> else return <RowView />
for more info take a look at searchParams next.js api, specifically for the server pages: https://nextjs.org/docs/app/api-reference/functions/use-search-params#server-components
@Sun bear If I get you correctly you are trying to create functionality that switches from grid view to row?
LionheadOP
Yes, you understood me correctly.
can you tell me if the application is expanding and it will always be convenient to use the context or is it better to connect the state manager? If so, which one can you recommend for Next.js
I read that for the client part it is recommended to use react query + zustand, what do you say about this?
Sun bear
In my opinion it comes down to preference. You wont know what you like until you try it. I personally use context for state that is exclusive to one branch of the component tree, and state management libraries for state that is used across different branches.
For state management libraries I think zustand is a best redux like state manager, but I personally use and recommend Jotai for most of my projects since it does not have nearly as much boiler plate as zustand and redux have, and it is much simpler to use. https://jotai.org/
For fetching state client-side react-query has been the best for a long time and it's really good, but try to fetch the state on the server as much as possible.
LionheadOP
Thank you very much for the detailed answer