Skip to content

Commit 26e92eb

Browse files
committed
fix(react-router): defer useCanGoBack to the server value while hydrating
The server builds a fresh single entry memory history for each request, so `useCanGoBack` renders `false` in the SSR markup. The browser preserves `history.state` across a reload, so after navigating and refreshing the client router starts on an entry whose `__TSR_index` is already non-zero. The client branch read that index during the hydration render, so the hydration output disagreed with the server markup and React reported a hydration mismatch. Gate the client value on hydration, the same way `resolveIsActive` already gates hash matching in `link.tsx`. While hydrating the hook returns `false`, which matches the server, and React then re-renders with the browser's real history index. Client-only renders are unaffected because `useHydrated` reads its client snapshot on the first render when there is no hydration pass.
1 parent 37877da commit 26e92eb

4 files changed

Lines changed: 163 additions & 2 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/react-router': patch
3+
---
4+
5+
Fix `useCanGoBack` reporting the browser history index during the hydration render, which contradicted the server markup and produced a hydration mismatch after a page refresh. The hook now defers to the server value while hydrating and reports the real history once hydration has settled.

‎docs/router/api/router/useCanGoBack.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ The `useCanGoBack` hook returns a boolean representing if the router history can
1616

1717
The router history index is reset after a navigation with [`reloadDocument`](./NavigateOptionsType.md#reloaddocument) set as `true`. This causes the router history to consider the new location as the initial one and will cause `useCanGoBack` to return `false`.
1818

19+
During server-side rendering the server builds a fresh single entry history for each request, so it cannot know how deep the browser's history is and always renders `false`. To keep the hydration render consistent with that markup, `useCanGoBack` also returns `false` while hydrating, then reports the browser's real history once hydration has settled. A server-rendered application therefore renders one frame of `false` before the value becomes accurate. If that frame is visible in your UI, render the dependent markup with [`ClientOnly`](./clientOnlyComponent.md) or keep the layout stable by disabling the control rather than removing it.
20+
1921
## Examples
2022

2123
### Showing a back button
Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { useStore } from '@tanstack/react-store'
22
import { isServer } from '@tanstack/router-core/isServer'
3+
import { useHydrated } from './ClientOnly'
34
import { useRouter } from './useRouter'
45

56
export function useCanGoBack() {
@@ -9,9 +10,18 @@ export function useCanGoBack() {
910
return router.stores.location.get().state.__TSR_index !== 0
1011
}
1112

12-
// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
13-
return useStore(
13+
/* eslint-disable react-hooks/rules-of-hooks -- condition is static */
14+
// The server renders a fresh single entry history per request, so it always
15+
// reports `false`. The browser preserves `history.state` across a reload and
16+
// can start on a deeper entry, so reporting the real index while hydrating
17+
// would contradict the server markup. Defer to the server value until
18+
// hydration has settled, then report the browser's history.
19+
const isHydrated = useHydrated()
20+
const canGoBack = useStore(
1421
router.stores.location,
1522
(location) => location.state.__TSR_index !== 0,
1623
)
24+
/* eslint-enable react-hooks/rules-of-hooks */
25+
26+
return isHydrated && canGoBack
1727
}
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import * as React from 'react'
2+
import { act, waitFor } from '@testing-library/react'
3+
import { hydrateRoot } from 'react-dom/client'
4+
import { renderToString } from 'react-dom/server'
5+
import { afterEach, describe, expect, test, vi } from 'vitest'
6+
import { createMemoryHistory } from '@tanstack/history'
7+
import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id'
8+
import { hydrate } from '../src/ssr/client'
9+
import {
10+
Outlet,
11+
RouterProvider,
12+
createRootRoute,
13+
createRoute,
14+
createRouter,
15+
useCanGoBack,
16+
} from '../src'
17+
import type { TsrSsrGlobal } from '../src/ssr/client'
18+
19+
declare global {
20+
interface Window {
21+
$_TSR?: TsrSsrGlobal
22+
}
23+
}
24+
25+
const testCleanups: Array<() => void | Promise<void>> = []
26+
27+
afterEach(async () => {
28+
while (testCleanups.length) {
29+
await testCleanups.pop()!()
30+
}
31+
vi.restoreAllMocks()
32+
window.$_TSR = undefined
33+
document.body.innerHTML = ''
34+
})
35+
36+
function makeRouteTree() {
37+
const rootRoute = createRootRoute({ component: Outlet })
38+
const indexRoute = createRoute({
39+
getParentRoute: () => rootRoute,
40+
path: '/',
41+
component: () => <h1>Page one</h1>,
42+
})
43+
const aboutRoute = createRoute({
44+
getParentRoute: () => rootRoute,
45+
path: '/about',
46+
component: function AboutComponent() {
47+
const canGoBack = useCanGoBack()
48+
return (
49+
<div data-testid="can-go-back">
50+
{canGoBack ? 'can go back' : 'cannot go back'}
51+
</div>
52+
)
53+
},
54+
})
55+
return rootRoute.addChildren([indexRoute, aboutRoute])
56+
}
57+
58+
describe('useCanGoBack during hydration', () => {
59+
test('does not report a hydration mismatch when the browser has history behind the entry', async () => {
60+
// The server builds a fresh single entry history per request, so it can
61+
// never know how deep the browser's history is.
62+
const serverRouter = createRouter({
63+
routeTree: makeRouteTree(),
64+
history: createMemoryHistory({ initialEntries: ['/about'] }),
65+
})
66+
serverRouter.isServer = true
67+
await serverRouter.load()
68+
const serverMatches = serverRouter.stores.matches.get()
69+
const serverHtml = renderToString(<RouterProvider router={serverRouter} />)
70+
expect(serverHtml).toContain('cannot go back')
71+
72+
// The browser preserves history.state across a reload, so the client
73+
// router starts on an entry whose __TSR_index is already 1.
74+
const clientRouter = createRouter({
75+
routeTree: makeRouteTree(),
76+
history: createMemoryHistory({ initialEntries: ['/', '/about'] }),
77+
})
78+
expect(clientRouter.stores.location.get().state.__TSR_index).toBe(1)
79+
80+
window.$_TSR = {
81+
router: {
82+
manifest: { routes: {} },
83+
dehydratedData: {},
84+
matches: serverMatches.map((match) => ({
85+
i: dehydrateSsrMatchId(match.id),
86+
u: match.updatedAt,
87+
s: match.status,
88+
l: match.loaderData,
89+
e: match.error,
90+
ssr: match.ssr,
91+
})),
92+
},
93+
h: vi.fn(),
94+
e: vi.fn(),
95+
c: vi.fn(),
96+
p: vi.fn(),
97+
buffer: [],
98+
initialized: false,
99+
}
100+
101+
await hydrate(clientRouter)
102+
103+
const container = document.createElement('div')
104+
container.innerHTML = serverHtml
105+
document.body.appendChild(container)
106+
107+
const recoverableHydrationErrors: Array<Error> = []
108+
let root!: ReturnType<typeof hydrateRoot>
109+
await act(async () => {
110+
root = hydrateRoot(container, <RouterProvider router={clientRouter} />, {
111+
onRecoverableError: (error) => {
112+
const messages = [
113+
error instanceof Error ? error.message : String(error),
114+
error instanceof Error && error.cause instanceof Error
115+
? error.cause.message
116+
: '',
117+
]
118+
if (
119+
messages.some((message) =>
120+
/hydration (?:failed|mismatch)|server rendered HTML.*client|server rendered text/i.test(
121+
message,
122+
),
123+
)
124+
) {
125+
recoverableHydrationErrors.push(error as Error)
126+
return
127+
}
128+
throw error
129+
},
130+
})
131+
testCleanups.push(async () => {
132+
await act(() => root.unmount())
133+
})
134+
await Promise.resolve()
135+
})
136+
137+
expect(recoverableHydrationErrors).toHaveLength(0)
138+
139+
// Once hydration has settled the hook reports the real browser history.
140+
await waitFor(() => {
141+
expect(container).toHaveTextContent('can go back')
142+
})
143+
})
144+
})

0 commit comments

Comments
 (0)