I’m building an e-commerce type website in Next.js where there are multiple sections of stores. Each store card has a heart icon to mark it as a favourite.
The same store can appear in:
multiple sections,
and multiple pages.
So if a user clicks the favourite icon on any store card, the heart icon should become filled everywhere that store appears across the site.
What I’m unsure about
Where and how should I fetch the favourite data so that every store card knows whether it is already marked as favourite or not?
Right now my approach is:
I fetch the favourite data using a server action inside the root layout,
then I initialize a Zustand store using a provider,
store cards read from the Zustand store to determine whether the heart icon is filled.
My question
Is this the best approach?
isn't it bad or blocking the load time if I fetch data in layout??
If not, what is the recommended way to structure this so that:
favourites stay synced across the whole app,
stores rendered in multiple places update immediately when favourited,
unnecessary network requests are avoided?
1 Reply 1
You have stumbled upon the classic problem of why I believe nextjs is overhyped :)
favourites stay synced across the whole app
You will want to have a centralized store. Whether your centralized store is on the server vs client is up to you and your existing architecture. I would recommend not using both. If it is in the client, you need to make sure that each hook is truly referencing the centralized context/store. If you don't already heavily use client state, then IMO server-side is the default option.
stores rendered in multiple places update immediately when favourited
This means you will need to push data from the server to the client, so you will need Server-Sent Events or WebSockets. Server-Sent Events is simpler. When the client receives an event, if it is storing state in the client, then it needs to update the client state; if it is storing state in the server, then it needs to refresh the page.
unnecessary network requests are avoided
You can update local state from the SSE/WebSocket event. If you use server state, then there will technically be an additional refresh request, but it's probably trivial and still more performant to just send that additional refresh request since you've already optimized for SSR.
Explore related questions
See similar questions with these tags.