Unverified Commit fbbd5380 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

[BF Cache]: skip lazyData fetch logic for inactive segments (#85142)

When `routerBfCache` is enabled, React's Activity API renders inactive
route segments offscreen to enable instant back/forward navigation.
However, the layout-router's lazy data fetching logic was incorrectly
triggering fetchServerResponse calls for these offscreen segments when
data was missing.

This PR adds an isActive prop to InnerLayoutRouter that tracks whether a
segment is currently visible via the existing `stateKey` check.
parent 2cc5f022
...@@ -437,6 +437,8 @@ function Router({ ...@@ -437,6 +437,8 @@ function Router({
// Root node always has `url` // Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl, url: canonicalUrl,
// Root segment is always active
isActive: true,
} }
}, [tree, cache, canonicalUrl]) }, [tree, cache, canonicalUrl])
......
...@@ -338,11 +338,13 @@ function InnerLayoutRouter({ ...@@ -338,11 +338,13 @@ function InnerLayoutRouter({
segmentPath, segmentPath,
cacheNode, cacheNode,
url, url,
isActive,
}: { }: {
tree: FlightRouterState tree: FlightRouterState
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
cacheNode: CacheNode cacheNode: CacheNode
url: string url: string
isActive: boolean
}) { }) {
const context = useContext(GlobalLayoutRouterContext) const context = useContext(GlobalLayoutRouterContext)
const parentNavPromises = useContext(NavigationPromisesContext) const parentNavPromises = useContext(NavigationPromisesContext)
...@@ -382,44 +384,48 @@ function InnerLayoutRouter({ ...@@ -382,44 +384,48 @@ function InnerLayoutRouter({
// navigation that will be able to fulfill it. We need to fetch more from // navigation that will be able to fulfill it. We need to fetch more from
// the server and patch the cache. // the server and patch the cache.
// Check if there's already a pending request. // Only fetch data for the active segment. Inactive segments (rendered
let lazyData = cacheNode.lazyData // offscreen for bfcache) should not trigger fetches.
if (lazyData === null) { if (isActive) {
/** // Check if there's already a pending request.
* Router state with refetch marker added let lazyData = cacheNode.lazyData
*/ if (lazyData === null) {
// TODO-APP: remove '' /**
const refetchTree = walkAddRefetch(['', ...segmentPath], fullTree) * Router state with refetch marker added
const includeNextUrl = hasInterceptionRouteInCurrentTree(fullTree) */
const navigatedAt = Date.now() // TODO-APP: remove ''
cacheNode.lazyData = lazyData = fetchServerResponse( const refetchTree = walkAddRefetch(['', ...segmentPath], fullTree)
new URL(url, location.origin), const includeNextUrl = hasInterceptionRouteInCurrentTree(fullTree)
{ const navigatedAt = Date.now()
flightRouterState: refetchTree, cacheNode.lazyData = lazyData = fetchServerResponse(
nextUrl: includeNextUrl new URL(url, location.origin),
? // We always send the last next-url, not the current when {
// performing a dynamic request. This is because we update flightRouterState: refetchTree,
// the next-url after a navigation, but we want the same nextUrl: includeNextUrl
// interception route to be matched that used the last ? // We always send the last next-url, not the current when
// next-url. // performing a dynamic request. This is because we update
context.previousNextUrl || context.nextUrl // the next-url after a navigation, but we want the same
: null, // interception route to be matched that used the last
} // next-url.
).then((serverResponse) => { context.previousNextUrl || context.nextUrl
startTransition(() => { : null,
dispatchAppRouterAction({ }
type: ACTION_SERVER_PATCH, ).then((serverResponse) => {
previousTree: fullTree, startTransition(() => {
serverResponse, dispatchAppRouterAction({
navigatedAt, type: ACTION_SERVER_PATCH,
previousTree: fullTree,
serverResponse,
navigatedAt,
})
}) })
})
return serverResponse return serverResponse
}) })
// Suspend while waiting for lazyData to resolve // Suspend while waiting for lazyData to resolve
use(lazyData) use(lazyData)
}
} }
// Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered. // Suspend infinitely as `changeByServerResponse` will cause a different part of the tree to be rendered.
// A falsey `resolvedRsc` indicates missing data -- we should not commit that branch, and we need to wait for the data to arrive. // A falsey `resolvedRsc` indicates missing data -- we should not commit that branch, and we need to wait for the data to arrive.
...@@ -461,6 +467,7 @@ function InnerLayoutRouter({ ...@@ -461,6 +467,7 @@ function InnerLayoutRouter({
// TODO-APP: overriding of url for parallel routes // TODO-APP: overriding of url for parallel routes
url: url, url: url,
isActive: isActive,
}} }}
> >
{content} {content}
...@@ -558,7 +565,8 @@ export default function OuterLayoutRouter({ ...@@ -558,7 +565,8 @@ export default function OuterLayoutRouter({
throw new Error('invariant expected layout router to be mounted') throw new Error('invariant expected layout router to be mounted')
} }
const { parentTree, parentCacheNode, parentSegmentPath, url } = context const { parentTree, parentCacheNode, parentSegmentPath, url, isActive } =
context
// Get the CacheNode for this segment by reading it from the parent segment's // Get the CacheNode for this segment by reading it from the parent segment's
// child map. // child map.
...@@ -691,6 +699,7 @@ export default function OuterLayoutRouter({ ...@@ -691,6 +699,7 @@ export default function OuterLayoutRouter({
tree={tree} tree={tree}
cacheNode={cacheNode} cacheNode={cacheNode}
segmentPath={segmentPath} segmentPath={segmentPath}
isActive={isActive && stateKey === activeStateKey}
/> />
{segmentBoundaryTriggerNode} {segmentBoundaryTriggerNode}
</RedirectBoundary> </RedirectBoundary>
......
...@@ -62,6 +62,7 @@ export const LayoutRouterContext = React.createContext<{ ...@@ -62,6 +62,7 @@ export const LayoutRouterContext = React.createContext<{
parentCacheNode: CacheNode parentCacheNode: CacheNode
parentSegmentPath: FlightSegmentPath | null parentSegmentPath: FlightSegmentPath | null
url: string url: string
isActive: boolean
} | null>(null) } | null>(null)
export const GlobalLayoutRouterContext = React.createContext<{ export const GlobalLayoutRouterContext = React.createContext<{
......
...@@ -457,7 +457,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -457,7 +457,7 @@ describe('Error overlay for hydration errors in App router', () => {
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/extra-nod..." tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/extra-nod..." tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]} ...>
<SegmentViewNode type="page" pagePath="(default)/..."> <SegmentViewNode type="page" pagePath="(default)/...">
<SegmentTrieNode> <SegmentTrieNode>
<ClientPageRoot Component={function Mismatch} searchParams={{}} params={{}}> <ClientPageRoot Component={function Mismatch} searchParams={{}} params={{}}>
...@@ -514,7 +514,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -514,7 +514,7 @@ describe('Error overlay for hydration errors in App router', () => {
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/p-under-p" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/p-under-p" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]} ...>
<SegmentViewNode type="page" pagePath="(default)/..."> <SegmentViewNode type="page" pagePath="(default)/...">
<SegmentTrieNode> <SegmentTrieNode>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
...@@ -570,7 +570,7 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -570,7 +570,7 @@ describe('Error overlay for hydration errors in App router', () => {
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/div-under-p" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/div-under-p" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]} ...>
<SegmentViewNode type="page" pagePath="(default)/..."> <SegmentViewNode type="page" pagePath="(default)/...">
<SegmentTrieNode> <SegmentTrieNode>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
......
...@@ -72,7 +72,7 @@ describe('hydration-error-count', () => { ...@@ -72,7 +72,7 @@ describe('hydration-error-count', () => {
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/html-diff" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/html-diff" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]} ...>
<SegmentViewNode type="page" pagePath="html-diff/..."> <SegmentViewNode type="page" pagePath="html-diff/...">
<SegmentTrieNode> <SegmentTrieNode>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment