Unverified Commit 01dd81eb authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Don't suspend client params on shallow URL updates (#99611)

With Cache Components enabled, a client page or layout that reads
`use(params)` or `use(searchParams)` showed the nearest Suspense
fallback on every `history.pushState` / `history.replaceState`, and when
going back and forward between those entries. The content was hidden for
a few hundred milliseconds each time, so a focused input lost focus and
dropped keystrokes.

Since the `params` and `searchParams` are already known on the client
during a render triggered by a navigation, there's no reason for them to
suspend. They were only suspending because we created a fresh promise on
each render.

We can instead mark the promise as fulfilled up front, by setting the
same `status` and `value` fields React sets once it has tracked a
promise. This is the internal protocol React uses to synchronously
unwrap resolved promises.

Ideally we would also avoid recomputing them on every render, only when
the router tree actually changes, but we can address that separately.

Thanks to @controversial, who found the cause and wrote the tests in
#99537.

Fixes #99512.
Co-authored-by: 's avatarLuke Deen Taylor <10377391+controversial@users.noreply.github.com>
parent 8136e9ce
...@@ -17,9 +17,6 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -17,9 +17,6 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
return cachedParams return cachedParams
} }
// We don't use makeResolvedReactPromise here because params
// supports copying with spread and we don't want to unnecessarily
// instrument the promise with spreadable properties of ReactPromise.
const promise = Promise.resolve(underlyingParams) const promise = Promise.resolve(underlyingParams)
const proxiedProperties = new Set<string>() const proxiedProperties = new Set<string>()
...@@ -58,6 +55,12 @@ function makeDynamicallyTrackedParamsWithDevWarnings( ...@@ -58,6 +55,12 @@ function makeDynamicallyTrackedParamsWithDevWarnings(
}, },
}) })
// Mark it as fulfilled the way React does once it has tracked it, so `use()`
// can unwrap it without suspending. This goes through the proxy, like React
// does, so a param named `value` isn't reported as a sync access.
;(proxiedPromise as any).status = 'fulfilled'
;(proxiedPromise as any).value = underlyingParams
CachedParams.set(underlyingParams, proxiedPromise) CachedParams.set(underlyingParams, proxiedPromise)
return proxiedPromise return proxiedPromise
} }
......
...@@ -10,6 +10,10 @@ function makeUntrackedParams(underlyingParams: Params): Promise<Params> { ...@@ -10,6 +10,10 @@ function makeUntrackedParams(underlyingParams: Params): Promise<Params> {
} }
const promise = Promise.resolve(underlyingParams) const promise = Promise.resolve(underlyingParams)
// Mark it as fulfilled the way React does once it has tracked it, so `use()`
// can unwrap it without suspending.
;(promise as any).status = 'fulfilled'
;(promise as any).value = underlyingParams
CachedParams.set(underlyingParams, promise) CachedParams.set(underlyingParams, promise)
return promise return promise
......
...@@ -76,6 +76,12 @@ function makeUntrackedSearchParamsWithDevWarnings( ...@@ -76,6 +76,12 @@ function makeUntrackedSearchParamsWithDevWarnings(
}, },
}) })
// Mark it as fulfilled the way React does once it has tracked it, so `use()`
// can unwrap it without suspending. This goes through the proxy, like React
// does, so a param named `value` isn't reported as a sync access.
;(proxiedPromise as any).status = 'fulfilled'
;(proxiedPromise as any).value = underlyingSearchParams
CachedSearchParams.set(underlyingSearchParams, proxiedPromise) CachedSearchParams.set(underlyingSearchParams, proxiedPromise)
return proxiedPromise return proxiedPromise
} }
......
...@@ -12,6 +12,10 @@ function makeUntrackedSearchParams( ...@@ -12,6 +12,10 @@ function makeUntrackedSearchParams(
} }
const promise = Promise.resolve(underlyingSearchParams) const promise = Promise.resolve(underlyingSearchParams)
// Mark it as fulfilled the way React does once it has tracked it, so `use()`
// can unwrap it without suspending.
;(promise as any).status = 'fulfilled'
;(promise as any).value = underlyingSearchParams
CachedSearchParams.set(underlyingSearchParams, promise) CachedSearchParams.set(underlyingSearchParams, promise)
return promise return promise
......
import { Suspense, type ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>
<Suspense fallback={<p>Loading...</p>}>{children}</Suspense>
</body>
</html>
)
}
'use client'
import { use } from 'react'
import { ShallowControls } from '../../shallow-controls'
export default function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
return (
<main>
<p id="id">{id}</p>
<ShallowControls />
</main>
)
}
'use client'
import { use } from 'react'
import { ShallowControls } from '../shallow-controls'
export default function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = use(searchParams)
return (
<main>
<p id="q">{q ?? '(none)'}</p>
<ShallowControls />
</main>
)
}
'use client'
import { use } from 'react'
import { ShallowControls } from '../../shallow-controls'
export default function Page({
params,
}: {
params: Promise<{ value: string }>
}) {
const { value } = use(params)
return (
<main>
<p id="value">{value}</p>
<ShallowControls />
</main>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
import { useState } from 'react'
export function ShallowControls() {
const [value, setValue] = useState('')
const searchParams = useSearchParams()
return (
<>
{/* Lets the test wait until the router has rendered the new URL. */}
<p id="rendered-q">{searchParams.get('q') ?? '(none)'}</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')
}
}}
/>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type { Playwright } from 'next-webdriver'
describe('client-params-shallow-routing', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function waitForRenderedQuery(browser: Playwright, q: string) {
await retry(async () => {
expect(await browser.elementByCss('#rendered-q').text()).toBe(q)
})
}
// Each keystroke writes the URL with replaceState.
async function typeIntoInput(browser: Playwright) {
await browser.elementByCss('#input').type('abc')
await waitForRenderedQuery(browser, 'abc')
}
// Enter writes the URL with pushState. Unlike clicking a button, this keeps
// the focus on the input.
async function pushState(browser: Playwright) {
await browser.keydown('Enter').keyup('Enter')
await waitForRenderedQuery(browser, 'pushed')
}
// If the page suspends, the nearest Suspense fallback hides the input, so it
// loses focus and the rest of the keystrokes are dropped.
async function expectInputToKeepFocus(browser: Playwright) {
expect(await browser.elementByCss('#input').getValue()).toBe('abc')
expect(await browser.eval('document.activeElement.id')).toBe('input')
}
async function expectNoSyncAccessWarning(browser: Playwright) {
expect(await browser.log()).not.toContainEqual(
expect.objectContaining({
message: expect.stringContaining(
'nextjs.org/docs/messages/sync-dynamic-apis'
),
})
)
}
describe('use(params) in a client page', () => {
it('should not suspend on replaceState', async () => {
const browser = await next.browser('/page-params/1')
await typeIntoInput(browser)
await expectInputToKeepFocus(browser)
expect(await browser.elementByCss('#id').text()).toBe('1')
})
it('should not suspend on pushState', async () => {
const browser = await next.browser('/page-params/1')
await typeIntoInput(browser)
await pushState(browser)
await expectInputToKeepFocus(browser)
expect(await browser.elementByCss('#id').text()).toBe('1')
})
it('should not warn about sync access when a param shares a name with a field of the promise', async () => {
const browser = await next.browser('/param-named-value/1')
await typeIntoInput(browser)
await pushState(browser)
expect(await browser.elementByCss('#value').text()).toBe('1')
await expectNoSyncAccessWarning(browser)
})
})
describe('use(searchParams) in a client page', () => {
it('should not suspend on replaceState', async () => {
const browser = await next.browser('/page-search-params')
await typeIntoInput(browser)
await expectInputToKeepFocus(browser)
expect(await browser.elementByCss('#q').text()).toBe('abc')
})
it('should not suspend on pushState', async () => {
const browser = await next.browser('/page-search-params')
await typeIntoInput(browser)
await pushState(browser)
await expectInputToKeepFocus(browser)
expect(await browser.elementByCss('#q').text()).toBe('pushed')
})
it('should not suspend when traversing between shallow history entries', async () => {
const browser = await next.browser('/page-search-params')
await typeIntoInput(browser)
await pushState(browser)
await browser.back()
await waitForRenderedQuery(browser, 'abc')
expect(await browser.elementByCss('#q').text()).toBe('abc')
await browser.forward()
await waitForRenderedQuery(browser, 'pushed')
expect(await browser.elementByCss('#q').text()).toBe('pushed')
await expectInputToKeepFocus(browser)
})
it('should not warn about sync access when a search param shares a name with a field of the promise', async () => {
const browser = await next.browser(
'/page-search-params?q=1&status=2&value=3'
)
expect(await browser.elementByCss('#q').text()).toBe('1')
await typeIntoInput(browser)
await pushState(browser)
await expectNoSyncAccessWarning(browser)
})
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
}
export default nextConfig
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