Unverified Commit 757a6e07 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

test: ensure that router identity stays stable when navigating (#77356)

I've added some tests to make sure the return value of `useRouter()`
stays stable when we dispatch an action to the action queue. Honestly, i
thought we had some, but it looks like we didn't.
The motivation for this is that
https://github.com/vercel/next.js/pull/76976 accidentally made
`useRouter()` return a new value after each action (or navigation). This
affected userspace code, which generally assumes that the return value
of `useRouter` is stable (which it should be).

---

The bug was here, in our `useReducer` (used for dispatching to the
actionQueue):


https://github.com/vercel/next.js/blob/5576edd3124277be568734d5d26923e9d75e520a/packages/next/src/client/components/use-reducer.ts#L45-L49

the `useCallback()` wrapping `dispatchCallback` also has
`dispatchCallback` listed in the dependencies, and `dispatchCallback` is
a fresh closure on every render, so in the end `useCallback` has no
effect.

as a result, the returned `dispatch` function is always changing, which
leads to a cascade of changes everywhere.
for example, we'll recreate `appRouter` each time `Router` rerenders
(which mainly happens because of an action/navigation), because
`dispatch` is one of its dependencies:

https://github.com/vercel/next.js/blob/5b9d66a9b872ad28336988b768af34852a85e9e3/packages/next/src/client/components/app-router.tsx#L355-L356

Originally, i also had a fix for that here, but in the meantime, the bad
memoization was fixed in https://github.com/vercel/next.js/pull/77354,
so this is just tests now.
parent 5b9d66a9
'use client'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
export function NavigateAndTrackRouterIdentity({ href }) {
const router = useRouter()
const [changedCount, setChangedCount] = useState(-1)
useEffect(() => {
setChangedCount((p) => p + 1)
}, [router])
const [navigationCount, setNavigationCount] = useState(0)
const navigate = () => {
setNavigationCount((p) => p + 1)
console.log('navigating to', href)
router.push(href)
}
return (
<>
<div>
navigations (without unmounting this component):{' '}
<span id="count-from-client-state">{navigationCount}</span>
</div>
<div>
router identity changes:{' '}
<span id="router-change-count">{changedCount}</span>
</div>
<button id="trigger-push" onClick={navigate}>
navigate
</button>
</>
)
}
import { connection } from 'next/server'
import { NavigateAndTrackRouterIdentity } from '../navigate'
export default async function Page({ searchParams }) {
// the page should be dynamic so that `router.push()` to the current path actually does a request + navigates.
await connection()
const { count: countStr = '0' } = await searchParams
const count = Number.parseInt(countStr)
return (
<>
{/* add a changing element to know that we actually navigated */}
<div id="count-from-server">{count}</div>
<NavigateAndTrackRouterIdentity
href={
'/use-router/same-page' +
'?' +
new URLSearchParams({ count: count + 1 })
}
/>
</>
)
}
import { NavigateToOther } from './navigate-to-other'
export default function Layout({ children }) {
return (
<>
<NavigateToOther />
<hr />
{children}
</>
)
}
'use client'
import { usePathname } from 'next/navigation'
import { NavigateAndTrackRouterIdentity } from '../navigate'
export function NavigateToOther() {
const pathname = usePathname()
const otherPage = pathname.endsWith('/one')
? pathname.replace('/one', '/two')
: pathname.endsWith('/two')
? pathname.replace('/two', '/one')
: (() => {
throw new Error('Unrecognized pathname: ' + pathname)
})()
return <NavigateAndTrackRouterIdentity href={otherPage} />
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return <h1>One</h1>
}
import { connection } from 'next/server'
export default async function Page() {
await connection()
return <h1>Two</h1>
}
......@@ -1011,4 +1011,65 @@ describe('app dir - navigation', () => {
})
})
}
describe('useRouter identity between navigations', () => {
it('should preserve identity when navigating to the same page', async () => {
const browser = await next.browser('/use-router/same-page')
expect(await browser.elementByCss('#count-from-server').text()).toBe('0')
expect(
await browser.elementByCss('#count-from-client-state').text()
).toBe('0')
expect(await browser.elementByCss('#router-change-count').text()).toBe(
'0'
)
for (let i = 1; i <= 3; i++) {
await browser.elementByCss('#trigger-push').click()
await retry(async () => {
expect(await browser.elementByCss('#count-from-server').text()).toBe(
`${i}`
)
// the client state is independent from the count we keep in the queryparam.
// we expect it to stay mounted and thus keep its own count.
// if it was getting unmounted, then its count of router changes would always stay at 0.
expect(
await browser.elementByCss('#count-from-client-state').text()
).toBe(`${i}`)
expect(
await browser.elementByCss('#router-change-count').text()
).toBe('0')
})
}
})
it('should preserve identity when navigating between different pages', async () => {
const browser = await next.browser('/use-router/shared-layout/one')
expect(await browser.elementByCss('h1').text()).toBe('One')
expect(
await browser.elementByCss('#count-from-client-state').text()
).toBe('0')
expect(await browser.elementByCss('#router-change-count').text()).toBe(
'0'
)
for (let i = 1; i <= 3; i++) {
await browser.elementByCss('#trigger-push').click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe(
i % 2 === 0 ? 'One' : 'Two'
)
// we expect the client part to stay mounted and thus keep its own count.
// if it was getting unmounted, then its count of router changes would always be 0.
expect(
await browser.elementByCss('#count-from-client-state').text()
).toBe(`${i}`)
expect(
await browser.elementByCss('#router-change-count').text()
).toBe('0')
})
}
})
})
})
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