Next.js Discord

Discord Forum

How to avoid re-fetching data in dynamic route segment server component

Unanswered
Daggertooth pike conger posted this in #help-forum
Open in Discord
Daggertooth pike congerOP
So I have a read-only page that displays various bits of information about a user, roughly sketched out in the attached image.

I'm using a dynamic route segment for the page that will match a couple of valid routes (e.g "personal-details" | "contact-details") which I am using to conditionally render different sections based on the route.

My problem is that all of the data that the page needs is bundled into one request (e.g GET /api/users/:userId), rather than one-per-page (e.g GET /api/users/:userId/personal-details), and I want to avoid making the request again every time the user navigates to a new section (and therefore re-rendering the dynamic route segment)

5 Replies

Daggertooth pike congerOP
Was hoping there was a purely server component solution without using context
well there is no solution that i know of. requests are independent and a subsequent request cannot use the data retrieved from a previous request
well, unless you want to cache the data itself
@Daggertooth pike conger Was hoping there was a purely server component solution without using context
You can cache the request results with unstable_cache but then you’ll have to consider other things like revalidation times, cache keys, stale data, etc etc. if you don’t wanna me constrained by these then the React context is the way.

Every time your layout mounts will fetch the data again and subsequent navigations under that same layout would share the already fetched data for the same user. No revalidation times, no stale data, no cache.

There’s no such thing as a React Context for Server Components.