Unverified Commit f9b85387 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

loading.tsx should have no effect on partial rendering when PPR is enabled (#59196)

Before PPR, the way instant navigations work in Next.js is we prefetch
everything up to the first route segment that defines a loading.js
boundary. The rest of the tree is defered until the actual navigation.
It does not take into account whether the data is dynamic — even if the
tree is completely static, it will still defer everything inside the
loading boundary.

The approach with PPR is different — we prefetch as deeply as possible,
and only defer when dynamic data is accessed. If so, we only defer the
nearest parent Suspense boundary of the dynamic data access, regardless
of whether the boundary is defined by loading.js or a normal <Suspense>
component in userspace.

This PR removes the partial behavior of loading.js when the PPR flag is
enabled. In effect, loading.js now acts like a regular Suspense boundary
with no additional special behavior.

Note that in practice this usually means we'll end up prefetching more
than we were before PPR, which may or may not be considered a
performance regression by some apps. The plan is to address this before
General Availability of PPR by introducing granular per-segment
fetching, so we can reuse as much of the tree as possible during both
prefetches and dynamic navigations. But during the beta period, we
should be clear about this trade off in our communications.

## Testing strategy

While I was writing a test, I noticed that it's currently pretty
difficult to test all the scenarios that PPR is designed to handle, so I
gave special attention to setting up a testing strategy that I hope will
make this easier going forward. The overall pattern is based on how
we've been testing concurrent rendering features in the React repo for
many years:

- In the e2e test, spin up an HTTP server for responding to requests
sent by the test app. This simulates the data service that would be used
in a real Next.js application, whether it's direct db access, an ORM, or
a higher-level data access layer. The e2e test can observe when
individual requests are received, and control the timing of when the
data is fulfilled, without needing to mock any lower level I/O. (We're
already using a similar pattern to [test fetch
deduping](https://github.com/vercel/next.js/blob/a3616d33edc40e7717b258f2636f280e30a3bccb/test/e2e/app-dir/app-fetch-deduping/app-fetch-deduping.test.ts#L8-L29).)
- Each time a request is received, write to an event log. Then assert on
the result of the log at different points throughout the test. This
helps catch subtle mistakes where the order of events is not expected,
or the same event happens more than it should.

(I wrote some test helpers, but to avoid early abstraction, I've
intentionally not moved them into a separate module.)

Closes NEXT-1779
parent e1a9c5ae
...@@ -56,7 +56,7 @@ export async function createComponentTree({ ...@@ -56,7 +56,7 @@ export async function createComponentTree({
ctx: AppRenderContext ctx: AppRenderContext
}): Promise<ComponentTree> { }): Promise<ComponentTree> {
const { const {
renderOpts: { nextConfigOutput }, renderOpts: { nextConfigOutput, experimental },
staticGenerationStore, staticGenerationStore,
componentMod: { componentMod: {
staticGenerationBailout, staticGenerationBailout,
...@@ -325,12 +325,43 @@ export async function createComponentTree({ ...@@ -325,12 +325,43 @@ export async function createComponentTree({
// We also want to bail out if there's no Loading component in the tree. // We also want to bail out if there's no Loading component in the tree.
let currentStyles = undefined let currentStyles = undefined
let childCacheNodeSeedData: CacheNodeSeedData | null = null let childCacheNodeSeedData: CacheNodeSeedData | null = null
if ( if (
!( // Before PPR, the way instant navigations work in Next.js is we
isPrefetch && // prefetch everything up to the first route segment that defines a
(Loading || !hasLoadingComponentInTree(parallelRoute)) // loading.tsx boundary. (We do the same if there's no loading
) // boundary in the entire tree, because we don't want to prefetch too
// much) The rest of the tree is defered until the actual navigation.
// It does not take into account whether the data is dynamic — even if
// the tree is completely static, it will still defer everything
// inside the loading boundary.
//
// This behavior predates PPR and is only relevant if the
// PPR flag is not enabled.
isPrefetch &&
(Loading || !hasLoadingComponentInTree(parallelRoute)) &&
// The approach with PPR is different — loading.tsx behaves like a
// regular Suspense boundary and has no special behavior.
//
// With PPR, we prefetch as deeply as possible, and only defer when
// dynamic data is accessed. If so, we only defer the nearest parent
// Suspense boundary of the dynamic data access, regardless of whether
// the boundary is defined by loading.tsx or a normal <Suspense>
// component in userspace.
//
// NOTE: In practice this usually means we'll end up prefetching more
// than we were before PPR, which may or may not be considered a
// performance regression by some apps. The plan is to address this
// before General Availability of PPR by introducing granular
// per-segment fetching, so we can reuse as much of the tree as
// possible during both prefetches and dynamic navigations. But during
// the beta period, we should be clear about this trade off in our
// communications.
!experimental.ppr
) { ) {
// Don't prefetch this child. This will trigger a lazy fetch by the
// client router.
} else {
// Create the child component // Create the child component
const { seedData, styles: childComponentStyles } = const { seedData, styles: childComponentStyles } =
await createComponentTree({ await createComponentTree({
......
...@@ -58,7 +58,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -58,7 +58,7 @@ export async function walkTreeWithFlightRouterState({
ctx: AppRenderContext ctx: AppRenderContext
}): Promise<FlightDataPath[]> { }): Promise<FlightDataPath[]> {
const { const {
renderOpts: { nextFontManifest }, renderOpts: { nextFontManifest, experimental },
query, query,
isPrefetch, isPrefetch,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -111,6 +111,8 @@ export async function walkTreeWithFlightRouterState({ ...@@ -111,6 +111,8 @@ export async function walkTreeWithFlightRouterState({
flightRouterState[3] === 'refetch' flightRouterState[3] === 'refetch'
const shouldSkipComponentTree = const shouldSkipComponentTree =
// loading.tsx has no effect on prefetching when PPR is enabled
!experimental.ppr &&
isPrefetch && isPrefetch &&
!Boolean(components.loading) && !Boolean(components.loading) &&
(flightRouterState || (flightRouterState ||
......
...@@ -3,6 +3,11 @@ import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils' ...@@ -3,6 +3,11 @@ import { check, getRedboxHeader, hasRedbox, waitFor } from 'next-test-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import stripAnsi from 'strip-ansi' import stripAnsi from 'strip-ansi'
// TODO: We should decide on an established pattern for gating test assertions
// on experimental flags. For example, as a first step we could all the common
// gates like this one into a single module.
const isPPREnabledByDefault = process.env.__NEXT_EXPERIMENTAL_PPR === 'true'
createNextDescribe( createNextDescribe(
'app dir - basic', 'app dir - basic',
{ {
...@@ -550,7 +555,12 @@ createNextDescribe( ...@@ -550,7 +555,12 @@ createNextDescribe(
}) })
// TODO-APP: Enable in development // TODO-APP: Enable in development
;(isDev ? it.skip : it)( ;(isDev ||
// When PPR is enabled, the shared layouts re-render because we prefetch
// from the root. This will be addressed before GA.
isPPREnabledByDefault
? it.skip
: it)(
'should not rerender layout when navigating between routes in the same layout', 'should not rerender layout when navigating between routes in the same layout',
async () => { async () => {
const browser = await next.browser('/same-layout/first') const browser = await next.browser('/same-layout/first')
...@@ -1334,7 +1344,12 @@ createNextDescribe( ...@@ -1334,7 +1344,12 @@ createNextDescribe(
}) })
// TODO-APP: disable failing test and investigate later // TODO-APP: disable failing test and investigate later
;(isDev ? it.skip : it)( ;(isDev ||
// When PPR is enabled, the shared layouts re-render because we prefetch
// from the root. This will be addressed before GA.
isPPREnabledByDefault
? it.skip
: it)(
'should render the template that is a server component and rerender on navigation', 'should render the template that is a server component and rerender on navigation',
async () => { async () => {
const browser = await next.browser('/template/servercomponent') const browser = await next.browser('/template/servercomponent')
......
import React from 'react'
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import React, { useState, use } from 'react'
const never = new Promise(() => {})
export function TriggerBadSuspenseFallback() {
const [shouldSuspend, setShouldSuspend] = useState(false)
if (shouldSuspend) {
use(never)
}
return (
<button
id="trigger-bad-suspense-fallback"
onClick={() => {
setShouldSuspend(true)
}}
>
Trigger Bad Suspense Fallback
</button>
)
}
import React from 'react'
export default async function LoadingInner() {
return <div id="loading-tsx">Loading [inner loading.tsx]...</div>
}
import React, { Suspense } from 'react'
import { TriggerBadSuspenseFallback } from './client'
import { getDynamicTestData, getStaticTestData } from './test-data-service'
async function Dynamic({ dataKey }) {
return (
<div id="dynamic">{await getDynamicTestData(`${dataKey} [dynamic]`)}</div>
)
}
async function Static({ dataKey }) {
return <div id="static">{await getStaticTestData(`${dataKey} [static]`)}</div>
}
export default async function Page({
params: { dataKey },
}: {
params: { dataKey: string }
}) {
return (
<>
<div id="container">
<Suspense fallback="Loading dynamic...">
<Dynamic dataKey={dataKey} />
</Suspense>
<Suspense fallback="Loading static...">
<Static dataKey={dataKey} />
</Suspense>
</div>
<TriggerBadSuspenseFallback />
</>
)
}
// NOTE: I've intentionally not yet moved these helpers into a shared module, to
// avoid early abstraction. I will if/when we start using them for other tests.
// They are based on the testing patterns we use all over the React codebase, so
// I'm reasonably confident in them.
const TEST_DATA_SERVICE_URL = process.env.TEST_DATA_SERVICE_URL
const ARTIFICIAL_DELAY = 200
async function getTestData(key: string, isStatic: boolean): Promise<string> {
const searchParams = new URLSearchParams({
key,
})
if (!TEST_DATA_SERVICE_URL) {
// If environment variable is not set, resolve automatically after a delay.
// This is so you can run the test app locally without spinning up a
// data server.
await new Promise<void>((resolve) =>
setTimeout(() => resolve(), ARTIFICIAL_DELAY)
)
return key
}
const response = await fetch(
TEST_DATA_SERVICE_URL + '?' + searchParams.toString(),
{
cache: isStatic ? 'force-cache' : 'no-store',
}
)
const text = await response.text()
if (response.status !== 200) {
throw new Error(text)
}
return text
}
export async function getStaticTestData(key: string): Promise<string> {
return getTestData(key, true)
}
export async function getDynamicTestData(key: string): Promise<string> {
return getTestData(key, false)
}
'use client'
import React, { useState } from 'react'
import Link from 'next/link'
export default function Start() {
const [href, setHref] = useState('')
return (
<form>
<input
type="text"
name="href"
onChange={(e) => setHref(e.target.value)}
value={href}
/>
{href === '' ? null : <Link href={href}>Navigate</Link>}
</form>
)
}
import React from 'react'
export default async function LoadingOuter() {
return <div id="loading-tsx">Loading [outer loading.tsx]...</div>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
},
}
module.exports = nextConfig
This diff is collapsed.
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