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

Fix: Unnecessary Suspense fallback triggered by URL update (#99612)

Every router state update is supposed to be wrapped in startTransition,
but restores weren't. A restore syncs the router with a userland
`history.pushState` / `history.replaceState`, a back/forward navigation
between those entries, or a page restored from the bfcache. The callers
dispatch it inside `startTransition`, but the action queue applied every
reducer result in a later microtask, after that scope had closed. So
anything that suspended on the new URL replaced the current content with
the nearest Suspense fallback.

The microtask came from wrapping the reducer in an async function, back
when reducers switched from throwing promises to returning them
(#56497). The queue already handles both kinds of results, so it now
calls the reducer directly and applies a synchronous result right away.
A reducer that throws is handled the same way a rejection was. This was
tried before in #77582 and reverted in #77909 because of a performance
regression that was seen internally.

Back/forward now gets React's usual popstate behavior: a Transition
that's scheduled during a `popstate` event renders synchronously.

This also removes the special case that dispatched the bfcache restore
as an urgent update. It was meant to stop the router from rendering a
stale MPA navigation and firing it again. But that state only exists in
a Transition that suspends and never commits, so a restore that's also a
Transition renders in the same pass. The bfcache test now covers this in
headless browsers too, by simulating the `pageshow` event.

Thanks to @controversial, who found the cause and wrote the original
test in #99537.
Co-authored-by: 's avatarLuke Deen Taylor <10377391+controversial@users.noreply.github.com>
parent 01dd81eb
...@@ -89,7 +89,7 @@ function runRemainingActions( ...@@ -89,7 +89,7 @@ function runRemainingActions(
} }
} }
async function runAction({ function runAction({
actionQueue, actionQueue,
action, action,
setState, setState,
...@@ -103,7 +103,11 @@ async function runAction({ ...@@ -103,7 +103,11 @@ async function runAction({
actionQueue.pending = action actionQueue.pending = action
const payload = action.payload const payload = action.payload
const actionResult = actionQueue.action(prevState, payload)
function handleError(err: Error) {
runRemainingActions(actionQueue, action, setState)
action.reject(err)
}
function handleResult(nextState: AppRouterState) { function handleResult(nextState: AppRouterState) {
// if we discarded this action, the state should also be discarded // if we discarded this action, the state should also be discarded
...@@ -129,12 +133,17 @@ async function runAction({ ...@@ -129,12 +133,17 @@ async function runAction({
action.resolve(nextState) action.resolve(nextState)
} }
let actionResult: ReducerState
try {
actionResult = actionQueue.action(prevState, payload)
} catch (err) {
handleError(err as Error)
return
}
// if the action is a promise, set up a callback to resolve it // if the action is a promise, set up a callback to resolve it
if (isThenable(actionResult)) { if (isThenable(actionResult)) {
actionResult.then(handleResult, (err) => { actionResult.then(handleResult, handleError)
runRemainingActions(actionQueue, action, setState)
action.reject(err)
})
} else { } else {
handleResult(actionResult) handleResult(actionResult)
} }
...@@ -226,10 +235,7 @@ export function createMutableActionQueue( ...@@ -226,10 +235,7 @@ export function createMutableActionQueue(
state: initialState, state: initialState,
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => dispatch: (payload: ReducerActions, setState: DispatchStatePromise) =>
dispatchAction(actionQueue, payload, setState), dispatchAction(actionQueue, payload, setState),
action: async (state: AppRouterState, action: ReducerActions) => { action: reducer,
const result = reducer(state, action)
return result
},
pending: null, pending: null,
last: null, last: null,
} }
......
...@@ -41,7 +41,7 @@ import { ...@@ -41,7 +41,7 @@ import {
type AppRouterActionQueue, type AppRouterActionQueue,
type GlobalErrorState, type GlobalErrorState,
} from './app-router-instance' } from './app-router-instance'
import { legacyUrgentBFCacheRestore, restore, traverse } from './navigator' import { restore, traverse } from './navigator'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError } from './redirect-error' import { isRedirectError } from './redirect-error'
import { pingVisibleLinks } from './links' import { pingVisibleLinks } from './links'
...@@ -279,7 +279,7 @@ function Router({ ...@@ -279,7 +279,7 @@ function Router({
// of the last MPA navigation. // of the last MPA navigation.
globalMutable.pendingMpaPath = undefined globalMutable.pendingMpaPath = undefined
legacyUrgentBFCacheRestore( restore(
new URL(window.location.href), new URL(window.location.href),
window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE
) )
......
...@@ -64,22 +64,6 @@ export function restore( ...@@ -64,22 +64,6 @@ export function restore(
notImplemented() notImplemented()
} }
// Never implemented, on purpose. This op exists only because the sequential
// queue expresses an MPA navigation as state (`pushRef.mpaNavigation`)
// consumed by a render-phase side effect, so a bfcache-restored page must
// reset that state with an urgent update before any other render can observe
// it and re-fire the navigation — urgency as a defense. The concurrent
// machine has no such hazard to defend against, and its single
// history/location owner handles the `pageshow` event itself, feeding it in
// as an ordinary restore — so this entry point won't be called at all once
// the shared callers are ported, and it dies with the sequential queue.
export function legacyUrgentBFCacheRestore(
_url: URL,
_historyState: AppHistoryState | undefined
): void {
notImplemented()
}
export function refresh(): void { export function refresh(): void {
notImplemented() notImplemented()
} }
......
...@@ -27,7 +27,6 @@ export { ...@@ -27,7 +27,6 @@ export {
replace, replace,
traverse, traverse,
restore, restore,
legacyUrgentBFCacheRestore,
refresh, refresh,
hmrRefresh, hmrRefresh,
} from './sequential-router-queue' } from './sequential-router-queue'
...@@ -152,30 +152,6 @@ export function restore( ...@@ -152,30 +152,6 @@ export function restore(
}) })
} }
/**
* The bfcache `pageshow` restore (see the pageshow handler in app-router.tsx).
* Unlike every other navigator operation, this dispatches as a deliberately
* urgent (non-transition) update: the restored state reset must render before
* anything else can observe the stale mpaNavigation state and re-fire the MPA
* navigation the restore exists to prevent. As a transition it would be
* interruptible, and an intervening urgent render could commit against the
* stale state first.
*
* This is a preserved legacy special case. It will not be carried into the
* concurrent router queue, which handles bfcache restore through its own
* design.
*/
export function legacyUrgentBFCacheRestore(
url: URL,
historyState: AppHistoryState | undefined
): void {
dispatchAppRouterAction({
type: ACTION_RESTORE,
url,
historyState,
})
}
export function refresh(): void { export function refresh(): void {
startTransition(() => { startTransition(() => {
dispatchAppRouterAction({ dispatchAppRouterAction({
......
'use client'
import { useSearchParams } from 'next/navigation'
import { Suspense, use, useState } from 'react'
// Stands in for a client data library that suspends on a cache keyed by the
// query.
const cache = new Map<string, Promise<string>>()
function load(q: string): Promise<string> {
let promise = cache.get(q)
if (promise === undefined) {
promise = Promise.resolve(q)
cache.set(q, promise)
}
return promise
}
function Content() {
const q = useSearchParams().get('q')
// Only suspends for the URLs written by the test, so the initial load
// doesn't depend on it.
const loaded = q === null ? '(none)' : use(load(q))
const [value, setValue] = useState('')
return (
<>
<p id="loaded">{loaded}</p>
<input
id="input"
value={value}
onChange={(event) => {
setValue(event.target.value)
window.history.replaceState(null, '', `?q=${event.target.value}`)
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
window.history.pushState(null, '', '?q=pushed')
}
}}
/>
</>
)
}
export default function Page() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Content />
</Suspense>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { check, retry } from 'next-test-utils'
describe('shallow-routing', () => { describe('shallow-routing', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -487,4 +487,37 @@ describe('shallow-routing', () => { ...@@ -487,4 +487,37 @@ describe('shallow-routing', () => {
}) })
}) })
}) })
describe('a component that suspends on data for the new URL', () => {
// The router applies the URL as a Transition, so React keeps showing the
// current content until the new content is ready. If it showed the
// Suspense fallback instead, the input would be hidden and lose focus.
async function expectInputToKeepFocus(browser, value: string) {
expect(await browser.elementByCss('#input').getValue()).toBe(value)
expect(await browser.eval('document.activeElement.id')).toBe('input')
}
async function waitForLoaded(browser, value: string) {
await retry(async () => {
expect(await browser.elementByCss('#loaded').text()).toBe(value)
})
}
it('should keep showing the current content on replaceState', async () => {
const browser = await next.browser('/suspends-on-search-params')
// Each keystroke writes the URL with replaceState.
await browser.elementByCss('#input').type('abc')
await waitForLoaded(browser, 'abc')
await expectInputToKeepFocus(browser, 'abc')
})
it('should keep showing the current content on pushState', async () => {
const browser = await next.browser('/suspends-on-search-params')
await browser.elementByCss('#input').click()
// Enter writes the URL with pushState.
await browser.keydown('Enter').keyup('Enter')
await waitForLoaded(browser, 'pushed')
await expectInputToKeepFocus(browser, '')
})
})
}) })
'use client' 'use client'
import React from 'react' import React from 'react'
import Link from 'next/link' import Link from 'next/link'
import { useRouter } from 'next/navigation'
export default function Page() { export default function Page() {
const router = useRouter()
const [counter, setCounter] = React.useState(0) const [counter, setCounter] = React.useState(0)
return ( return (
<div> <div>
...@@ -10,6 +12,18 @@ export default function Page() { ...@@ -10,6 +12,18 @@ export default function Page() {
<button onClick={() => setCounter((c) => c + 1)}> <button onClick={() => setCounter((c) => c + 1)}>
Trigger Re-Render Trigger Re-Render
</button> </button>
<button
id="transition"
onClick={() => React.startTransition(() => setCounter((c) => c + 1))}
>
Trigger Re-Render in a Transition
</button>
<button
id="push-external"
onClick={() => router.push('https://example.vercel.sh')}
>
Push External Page
</button>
<div id="counter">{counter}</div> <div id="counter">{counter}</div>
<Link href="https://example.vercel.sh">External Page</Link> <Link href="https://example.vercel.sh">External Page</Link>
</div> </div>
......
import { Server } from 'http' import { Server } from 'http'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { findPort, startStaticServer, stopApp } from 'next-test-utils' import { findPort, retry, startStaticServer, stopApp } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
const itHeaded = process.env.HEADLESS ? it.skip : it const itHeaded = process.env.HEADLESS ? it.skip : it
...@@ -82,4 +82,45 @@ describe('bfcache-routing', () => { ...@@ -82,4 +82,45 @@ describe('bfcache-routing', () => {
) )
} }
) )
it('should not repeat an MPA navigation when the page is restored from bfcache', async () => {
let externalRequests = 0
const browser = await next.browser('/index.html', {
baseUrl: port,
async beforePageLoad(page) {
// A 204 response cancels the navigation, so the page stays where it
// is while the router is still waiting for the MPA navigation.
await page.route('https://example.vercel.sh/**', (route) => {
externalRequests++
return route.fulfill({ status: 204 })
})
},
})
await browser.elementByCss('#push-external').click()
await retry(async () => {
expect(externalRequests).toBe(1)
})
// Headless browsers don't use the bfcache, so simulate the event that's
// fired when a page is restored from it.
await browser.eval(
`window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))`
)
// A Transition anywhere in the app also renders the router's pending
// updates. If the router still rendered the MPA navigation, it would
// suspend and fire the navigation again.
await browser.elementByCss('#transition').click()
await retry(async () => {
expect(await browser.elementByCss('#counter').text()).toBe('1')
})
expect(externalRequests).toBe(1)
// A new MPA navigation to the same URL still works after the restore.
await browser.elementByCss('#push-external').click()
await retry(async () => {
expect(externalRequests).toBe(2)
})
})
}) })
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