Unverified Commit 2e9538bd authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Remove unnecessary re render on link reveal (#74670)

The Link component initiates a prefetch whenever it enters the viewport,
but currently the implementation works by setting an `isVisible` state
to true, rerendering the component, and calling `router.prefetch` inside
a `useEffect` hook. This extra render is not necessary — we can initiate
the prefetch directly inside the IntersectionObserver's event handler.

The bulk of the changes in this commit involve removing the use of the
`useIntersection` abstraction and inlining the IntersectionObserver into
the Link module. The removal of this indirection will make it easier to
add more sophisticated scheduling improvements, like canceling the
prefetch on viewport exit, and increasing the priority of the prefetch
during hover.
parent 65db12fe
...@@ -621,5 +621,6 @@ ...@@ -621,5 +621,6 @@
"620": "A required parameter (%s) was not provided as %s received %s in getStaticPaths for %s", "620": "A required parameter (%s) was not provided as %s received %s in getStaticPaths for %s",
"621": "Required root params (%s) were not provided in generateStaticParams for %s, please provide at least one value for each.", "621": "Required root params (%s) were not provided in generateStaticParams for %s, please provide at least one value for each.",
"622": "A required root parameter (%s) was not provided in generateStaticParams for %s, please provide at least one value.", "622": "A required root parameter (%s) was not provided in generateStaticParams for %s, please provide at least one value.",
"623": "Invalid quality prop (%s) on \\`next/image\\` does not match \\`images.qualities\\` configured in your \\`next.config.js\\`\\nSee more info: https://nextjs.org/docs/messages/next-image-unconfigured-qualities" "623": "Invalid quality prop (%s) on \\`next/image\\` does not match \\`images.qualities\\` configured in your \\`next.config.js\\`\\nSee more info: https://nextjs.org/docs/messages/next-image-unconfigured-qualities",
"624": "Internal Next.js Error: createMutableActionQueue was called more than once"
} }
This diff is collapsed.
...@@ -90,22 +90,14 @@ export type PrefetchTask = { ...@@ -90,22 +90,14 @@ export type PrefetchTask = {
*/ */
hasBackgroundWork: boolean hasBackgroundWork: boolean
/**
* True if the prefetch is blocked by network data. We remove tasks from the
* queue once they are blocked, and add them back when they receive data.
*
* isBlocked also indicates whether the task is currently in the queue; tasks
* are removed from the queue when they are blocked. Use this to avoid
* queueing the same task multiple times.
*/
isBlocked: boolean
/** /**
* The index of the task in the heap's backing array. Used to efficiently * The index of the task in the heap's backing array. Used to efficiently
* change the priority of a task by re-sifting it, which requires knowing * change the priority of a task by re-sifting it, which requires knowing
* where it is in the array. This is only used internally by the heap * where it is in the array. This is only used internally by the heap
* algorithm. The naive alternative is indexOf every time a task is queued, * algorithm. The naive alternative is indexOf every time a task is queued,
* which has O(n) complexity. * which has O(n) complexity.
*
* We also use this field to check whether a task is currently in the queue.
*/ */
_heapIndex: number _heapIndex: number
} }
...@@ -173,7 +165,7 @@ export function schedulePrefetchTask( ...@@ -173,7 +165,7 @@ export function schedulePrefetchTask(
key: RouteCacheKey, key: RouteCacheKey,
treeAtTimeOfPrefetch: FlightRouterState, treeAtTimeOfPrefetch: FlightRouterState,
includeDynamicData: boolean includeDynamicData: boolean
): void { ): PrefetchTask {
// Spawn a new prefetch task // Spawn a new prefetch task
const task: PrefetchTask = { const task: PrefetchTask = {
key, key,
...@@ -182,7 +174,6 @@ export function schedulePrefetchTask( ...@@ -182,7 +174,6 @@ export function schedulePrefetchTask(
hasBackgroundWork: false, hasBackgroundWork: false,
includeDynamicData, includeDynamicData,
sortId: sortIdCounter++, sortId: sortIdCounter++,
isBlocked: false,
_heapIndex: -1, _heapIndex: -1,
} }
heapPush(taskHeap, task) heapPush(taskHeap, task)
...@@ -195,6 +186,27 @@ export function schedulePrefetchTask( ...@@ -195,6 +186,27 @@ export function schedulePrefetchTask(
// If they have different priorities, it also ensures they are processed in // If they have different priorities, it also ensures they are processed in
// the optimal order. // the optimal order.
ensureWorkIsScheduled() ensureWorkIsScheduled()
return task
}
export function bumpPrefetchTask(task: PrefetchTask): void {
// Bump the prefetch task to the top of the queue, as if it were a fresh
// task. This is essentially the same as canceling the task and scheduling
// a new one, except it reuses the original object.
//
// The primary use case is to increase the relative priority of a Link-
// initated prefetch on hover.
// Assign a new sort ID. Higher sort IDs are higher priority.
task.sortId = sortIdCounter++
if (task._heapIndex !== -1) {
// The task is already in the queue.
heapResift(taskHeap, task)
} else {
heapPush(taskHeap, task)
}
ensureWorkIsScheduled()
} }
function ensureWorkIsScheduled() { function ensureWorkIsScheduled() {
...@@ -263,12 +275,14 @@ function onPrefetchConnectionClosed(): void { ...@@ -263,12 +275,14 @@ function onPrefetchConnectionClosed(): void {
*/ */
export function pingPrefetchTask(task: PrefetchTask) { export function pingPrefetchTask(task: PrefetchTask) {
// "Ping" a prefetch that's already in progress to notify it of new data. // "Ping" a prefetch that's already in progress to notify it of new data.
if (!task.isBlocked) { if (
// Prefetch is already queued. // Check if prefetch is already queued.
// TODO: Check if task was canceled, too
task._heapIndex !== -1
) {
return return
} }
// Unblock the task and requeue it. // Add the task back to the queue.
task.isBlocked = false
heapPush(taskHeap, task) heapPush(taskHeap, task)
ensureWorkIsScheduled() ensureWorkIsScheduled()
} }
...@@ -300,10 +314,8 @@ function processQueueInMicrotask() { ...@@ -300,10 +314,8 @@ function processQueueInMicrotask() {
case PrefetchTaskExitStatus.Blocked: case PrefetchTaskExitStatus.Blocked:
// The task is blocked. It needs more data before it can proceed. // The task is blocked. It needs more data before it can proceed.
// Keep the task out of the queue until the server responds. // Keep the task out of the queue until the server responds.
task.isBlocked = true
// Continue to the next task
heapPop(taskHeap) heapPop(taskHeap)
// Continue to the next task
task = heapPeek(taskHeap) task = heapPeek(taskHeap)
continue continue
case PrefetchTaskExitStatus.Done: case PrefetchTaskExitStatus.Done:
......
...@@ -174,6 +174,8 @@ function dispatchAction( ...@@ -174,6 +174,8 @@ function dispatchAction(
} }
} }
let globalActionQueue: AppRouterActionQueue | null = null
export function createMutableActionQueue( export function createMutableActionQueue(
initialState: AppRouterState initialState: AppRouterState
): AppRouterActionQueue { ): AppRouterActionQueue {
...@@ -189,5 +191,22 @@ export function createMutableActionQueue( ...@@ -189,5 +191,22 @@ export function createMutableActionQueue(
last: null, last: null,
} }
if (typeof window !== 'undefined') {
// The action queue is lazily created on hydration, but after that point
// it doesn't change. So we can store it in a global rather than pass
// it around everywhere via props/context.
if (globalActionQueue !== null) {
throw new Error(
'Internal Next.js Error: createMutableActionQueue was called more ' +
'than once'
)
}
globalActionQueue = actionQueue
}
return actionQueue return actionQueue
} }
export function getCurrentAppRouterState(): AppRouterState | null {
return globalActionQueue !== null ? globalActionQueue.state : null
}
import { Suspense } from 'react'
type Params = {
pageNumber: string
}
async function Content({ params }: { params: Promise<Params> }) {
const { pageNumber } = await params
return 'Content of page ' + pageNumber
}
export default async function LinkCancellationTargetPage({
params,
}: {
params: Promise<Params>
}) {
return (
<Suspense fallback="Loading...">
<Content params={params} />
</Suspense>
)
}
export async function generateStaticParams(): Promise<Array<Params>> {
const result: Array<Params> = []
for (let n = 1; n <= 1; n++) {
result.push({ pageNumber: n.toString() })
}
return result
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
type PaginationConfig = {
start: number
end: number
}
export default function LinkCancellationPage() {
const [areLinksVisible, setLinksVisibility] = useState(false)
const [showMoreLinks, setShowMoreLinks] = useState(false)
return (
<>
<p>
This page is used to test that a prefetch scheduled when a Link enters
the viewport is cancelled when the Link exits. The visibility toggle
does not affect whether the links are mounted, only whether they are
visible (using the `hidden` attribute).
</p>
<label>
<input
type="checkbox"
checked={areLinksVisible}
onChange={() => setLinksVisibility(!areLinksVisible)}
/>
{areLinksVisible ? 'Hide' : 'Show'} Links
</label>
<ul id="links-container" hidden={!areLinksVisible}>
<Links start={1} end={7} />
{showMoreLinks ? (
<Links start={8} end={10} />
) : (
<li>
<form>
<button
id="show-more-links"
formAction={() => setShowMoreLinks(true)}
>
Show more links
</button>
</form>
</li>
)}
</ul>
</>
)
}
function Links({ start, end }: PaginationConfig) {
const links: Array<React.ReactNode> = []
for (let pageNumber = start; pageNumber <= end; pageNumber++) {
links.push(
<li key={pageNumber}>
<Link href={'/cancellation/' + pageNumber}>
Link to page {pageNumber}
</Link>
</li>
)
}
return links
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
dynamicIO: true,
clientSegmentCache: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache prefetch scheduling', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (isNextDev || skipped) {
test('prefetching is disabled', () => {})
return
}
it('increases the priority of a viewport-initiated prefetch on hover', async () => {
// TODO: This works because we bump the prefetch task to the front of the
// queue on mouseenter. But there's a flaw: if another link enters the
// viewport while the first link is still being hovered, the second link
// will go ahead of it in the queue. In other words, we currently don't
// treat mouseenter as a higher priority signal than "viewport enter". To
// fix this, we need distinct priority levels for hover and viewport; the
// last-in-first-out strategy is not sufficient for the desired behavior.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/cancellation', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
const checkbox = await browser.elementByCss('input[type="checkbox"]')
await act(
async () => {
// Reveal the links to start prefetching, but block the responses from
// reaching the client. This will initiate prefetches for the route
// trees, but it won't start prefetching any segment data yet until the
// trees have loaded.
await act(async () => {
await checkbox.click()
}, 'block')
// Hover over a link to increase its relative priority.
const link2 = await browser.elementByCss('a[href="/cancellation/2"]')
await link2.hover()
// Hover over a different link to increase its relative priority.
const link5 = await browser.elementByCss('a[href="/cancellation/5"]')
await link5.hover()
},
// Assert that the segment data is prefetched in the expected order.
[
// The last link we hovered over should be the first to prefetch.
{ includes: 'Content of page 5' },
// The second-to-last link we hovered over should come next.
{ includes: 'Content of page 2' },
// Then all the other links come after that. (We don't need to assert
// on every single prefetch response. I picked one of them arbitrarily.)
{ includes: 'Content of page 4' },
]
)
})
})
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