How do you handle data fetching during navigation?
Unanswered
Lagotto Romagnolo posted this in #help-forum
Lagotto RomagnoloOP
I’m using the Page Router with getInitialProps.
Let’s say I’m navigating between pageA and pageB (e.g., Page A → Page B → Page A).
I want users to always see the most up-to-date data, not stale content.
How do you typically approach data fetching in this scenario?
Here are some options I’ve considered:
(1) Stale-while-revalidate (e.g., using useQuery - tanstack query)
This works well for client-side rendering (CSR), as it allows showing cached data first while revalidating in the background.
However, it has a few drawbacks:
- It often results in double fetching during hydration
- Since revalidation happens in the background, users may briefly see stale data before fresh data arrives.
- You also need to manually control the query using flags like isFetching, keepPreviousData, or enabled.
(2) Fetching inside getInitialProps for both SSR and CSR
This approach ensures data is always fetched before rendering, whether on the server or during client-side navigation.
The trade-off is that client-side transitions can feel slow, since users must wait for the data to be fully loaded before the page renders.
(3) Handling SSR and CSR differently
SSR: Fetch data on the server and hydrate the page with it.
CSR: Use startTransition to show a loading state at eventHandler or clear the data at getInitialProps so that React Suspense can handle the loading on the destination page.
Let’s say I’m navigating between pageA and pageB (e.g., Page A → Page B → Page A).
I want users to always see the most up-to-date data, not stale content.
How do you typically approach data fetching in this scenario?
Here are some options I’ve considered:
(1) Stale-while-revalidate (e.g., using useQuery - tanstack query)
This works well for client-side rendering (CSR), as it allows showing cached data first while revalidating in the background.
However, it has a few drawbacks:
- It often results in double fetching during hydration
- Since revalidation happens in the background, users may briefly see stale data before fresh data arrives.
- You also need to manually control the query using flags like isFetching, keepPreviousData, or enabled.
(2) Fetching inside getInitialProps for both SSR and CSR
This approach ensures data is always fetched before rendering, whether on the server or during client-side navigation.
The trade-off is that client-side transitions can feel slow, since users must wait for the data to be fully loaded before the page renders.
(3) Handling SSR and CSR differently
SSR: Fetch data on the server and hydrate the page with it.
CSR: Use startTransition to show a loading state at eventHandler or clear the data at getInitialProps so that React Suspense can handle the loading on the destination page.