Next.js Discord

Discord Forum

Server component re-fetches data on every tab change with dynamic route

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hi everyone,
I'm facing an issue with dynamic routes in Next.js. My route structure is:
/match/[id]/[name]/[tab]

I'm using router.push() to switch between tabs, and the problem is that the getFixtureDetails() function at the top of the page is being called again on every tab change.
However, I'm already fetching the data once on initial load and passing it as props to all tab components. When switching tabs, only the displayed component should change - the API request shouldn't be repeated.

My question: How can I prevent the server component from restarting when the tab changes, while maintaining the route structure as /match/[id]/[name]/[tab]?
I want to fetch the data only once and use the same data across tab changes.
Thanks!
Answered by alfonsüs ardani
i see. you can use history.pushState to do shallow routing and if i remember correctly, and client component with useParams or usePathname would also react acordingly
View full answer

5 Replies

I'm using router.push() to switch between tabs always do server-side navigation. if you want to not repeat API request, i suggest looking on data cache usage such as using fetch() if external data, or unstable_cache if using async libraries.

unstable_cache, such as this (neatly wrapped in my own custom datacache function) makes it easier to make navigation feels like client-side while also not overengineering the navigation to force shallow or reuse data on client or whatever
@alfonsüs ardani `I'm using router.push() to switch between tabs` always do server-side navigation. if you want to not repeat API request, i suggest looking on data cache usage such as using `fetch()` if external data, or `unstable_cache` if using async libraries. unstable_cache, such as this (neatly wrapped in my own custom datacache function) makes it easier to make navigation feels like client-side while also not overengineering the navigation to force shallow or reuse data on client or whatever
Cape lionOP
Thanks for the suggestion, However, I don't want to use caching - I just want to prevent re-fetching when switching tabs. The data is already fetched once on initial load, so there's no need to fetch it again when only the tab parameter changes. I'm looking for a way to keep the same data in memory across tab changes without hitting the API again.
i see. you can use history.pushState to do shallow routing and if i remember correctly, and client component with useParams or usePathname would also react acordingly
Answer
cc @Cape lion
Cape lionOP
thank you, it's working this way