Skip to content

Commit a55c2b5

Browse files
authored
fix(router): location state belongs to the entry on screen; evicted same-route back/forward restores its page (#1029, #1030) (#1033)
* fix(router): useLocationState changes with its entry's tree, not before it (#1029) A mounted useLocationState reader received the destination entry's state as soon as the router pushed the entry (on back/forward, at the popstate event), in a render of its own. For as long as a navigation was held, the page being left rendered with the next entry's state: a "load more" list showed the current page's items twice until the next page landed. The hook read history.state through useSyncExternalStore, and tx.commit told it with a window event. A store snapshot is the latest value in every tree at once, so it cannot stay behind in the tree a transition is holding. Location state now rides the route-state notification. A commit site moves an identity on the event controller (commitLocationState); the hook keeps its slot in React state and re-reads history.state when the identity moves. NavigationProvider already flushes that notification inside the payload update, so the read takes the payload's lane and commits with the destination's tree. useSyncExternalStore stays for its server snapshot. - push, replace, back/forward (cached restore and refetch) and server-set state on a navigation commit with the tree. - A revalidate:false navigation and a server action's state commit no tree and are delivered at once, as before. - clientUrls(): OptimisticLocation carries the entry the navigation will push, so the optimistic destination reads its own state on its first render instead of the entry being left. - The __rsc_locationstate window event and its dispatch sites are gone. - A reader whose slot a commit leaves as it was sets no state. - renderRoute: navigations commit through the controller, router.navigate() takes state/replace, and a popstate event is a back/forward onto the current history.state. The hook carries "use no memo": compiled by the React Compiler it grows a 29-slot memo cache (296B gzip in the router chunk). Router chunk on cloudflare-basic: 47077B -> 47100B gzip (limit 47104B). * test(e2e): location state commits with its entry's tree, in both apps (#1029) Browser coverage for #1029 in the router test-app and cloudflare-basic, dev and production, with the bodies shared in tests/shared-e2e. - The load-more fixture loads its page through a loader (`?hold=<ms>` delays it) and lists carried items plus the loader's page with no duplicate filter. `location-state.commit` holds a navigation for 2.5s and checks the screen during the hold, every DOM state in between and every list the fixture committed; then back/forward across cached entries and a return to an evicted entry, with a reader in a layout the two #994 fixtures now share. - The slow clientUrls group gets a reader in chrome outside the group, in the group layout and in each page: the optimistic destination reads the state its navigation carries, held content keeps its entry's state until the canonical commit, and a superseded or cancelled navigation leaves none behind. - The render-stability pages get a useLocationState probe: same render and commit counts as on main. - cloudflare-basic's dogfood unit test seeds the list's loader and pins the pending window through renderRoute. No route was added or renamed. * docs: location state changes with its entry's page; drop the load-more duplicate filter (#1029) - skills/hooks/state.md: the contract ("When a reader sees an entry's state") with a table per kind of change, and the load-more example as the plain concatenation. The paragraph that described the duplicate filter as a workaround is gone. - skills/client-urls, docs/client-urls.md: inside the optimistic branch useLocationState reads the state the navigation carries; outside it and in held content, the committed entry's. - skills/testing, docs/testing.md: router.navigate(url, { state, loaders }) for a component across a pending navigation, and a popstate event as a back/forward. - docs/internal/feature-map.md, feature-file-map.md: location state on the route-state notification, the commit sites, and why the hook is React state with useSyncExternalStore kept for the server snapshot only. - docs site hooks reference, shallow-navigation design note: same rule. * fix(router): location state is NavigationProvider state, read by context (#1029) A reader that mounted while a navigation was pending read the destination entry's state in the tree still on screen: useLocationState took its first value from history.state, which has already moved by then. The first fix covered readers that were mounted and left this one open. The location state of the entry on screen is now React state owned by NavigationProvider, set in the same update as the payload and delivered by LocationStateContext. A transition React holds renders the destination's value; an urgent render of the content on screen, a reader mounting there included, renders the value of the entry being left. The hook is a context read behind the per-reader hydration snapshot: no identity, no mirror ref, no subscription, no frozen first read. - Every commit site hands the controller the entry state it pushed, restored or merged (EventController.commitLocationState(entryState)); the snapshot is built from that object, under the version and clearOnReload rules, not from a later read of history.state. The provider takes it next to setPayload. A commit no payload follows (shallow navigation, a commit that keeps every segment, an action's state) is marked treeless and taken with that commit's state notification, in the batch of the location. - A value keeps its identity when a navigation carries the reader's own value forward or an action changes another slot; any other object is a new value, and a structured clone of what the caller passed. - An action's state is added to what readers hold instead of re-reading the entry, so a flash value on screen survives it. - write()/delete() and the flash clear change history only: readers see them when the entry is next restored. A flash value is shown until the entry's state is next committed. - Outside a NavigationProvider a reader has no location state. - The "use no memo" directive is gone. Router chunk 47077B -> 47262B gzip; limit raised 46KB -> 47KB with a dated note (47167B with the directive, so it would not have fit either). - renderRoute commits through the same calls: its popstate listener is the bridge's registerLinkInterception, and router.navigate() writes history only for `state` or `replace: true`. - The optimistic clientUrls() entry state is built only when the group presents the target. * test(e2e): a reader mounted during a held navigation reads the entry on screen (#1029) Both apps, dev and production: the load-more fixture mounts a second reader of the carried items on demand. Pressed while the next page's loader holds the navigation, it mounts in the page still on screen and must read that page's entry, then change with the list. The DOM sampler flags any state in which the late reader disagrees with the list it is in. The cloudflare-basic dogfood test covers the same through renderRoute. The test-app's load-more and app-version routes move to their own urls() module, included at the same paths and names, so location-state.tsx keeps its existing patterns untouched. * fix(router): back/forward to an evicted same-route entry restores that entry's page (#1030) Going back or forward to an entry of the same route that differs only in search params, after the history cache dropped it, changed the URL and the entry's location state and left the page being left on screen: a load-more list past 20 pages showed the wrong page's items on Back. Cause: the partial fetch tells the server which page the client is on (X-RSC-Router-Client-Path) from the transaction's URL, window.location at the time the transaction is created. On a back/forward the popstate event has already moved it to the target, so the server diffed the target against itself: on the same route nothing revalidates, the diff is empty, and the client commits without a tree. A different route still got its segments, which is why only the same-route case showed. A traversal now names the store's URL, the committed entry's, as the leave-intercept path already did for the same reason. An intercept restore keeps naming the intercept's source; push and replace keep the transaction's URL. Tests: partial-update unit tests for the three cases, and an e2e in both apps, dev and production, that evicts through the same route and returns with the refetch held by its loader. * docs: location state is the entry on screen's; #1030 changelog; the popstate limit (#1029, #1030, #1031) The hooks skill and the docs-site page state the contract as built: a reader gets an entry's location state with that entry's page, including a reader that mounts while a navigation is pending, and what follows from the provider holding it (identity of values, write()/delete(), flash, a reader outside the provider). Both name the limit that remains: usePathname and useSearchParams still change at popstate on back/forward (#1031). CHANGELOG: the #1029 entry is rewritten around the same contract and lists every change in when a reader updates that an existing app could notice; a #1030 entry is added. Also: the optimistic clientUrls() value is the object the navigation passed and becomes the entry's copy at the commit (documented, not cloned); renderRoute's navigate() history options and its popstate listener; the internal feature maps and the shallow-navigation design note follow the provider-owned delivery. * test(e2e): the offscreen-prefetch test waits for the streamed layout before measuring cloudflare-basic's `default-prefetch-none › an offscreen viewport override waits for intersection` read the link's position right after the shell hydrated. When the document streams the layout as its own segment, React reveals it a moment later (measured: 179ms); until then the link sits in a hidden `S:1` node and has no box: `Expected: > 920 Received: 0`. The three client-urls-slow tests this branch adds run next to it in a local two-worker dev run, and with them it lost that race in 2 of 2 full runs and 3 of 3 runs of the nine files around it. Alone it passed 4 of 4, and on the same source without those three tests the nine files pass. On origin/main it passed 2 of 2 full dev runs. Wait for the link to be visible, then measure. The assertion is unchanged.
1 parent eed288b commit a55c2b5

63 files changed

Lines changed: 3688 additions & 625 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/docs/content/docs/rango/reference/hooks.mdx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,15 +334,19 @@ const state = useLocationState(ProductState); // { name; price } | undefined
334334
</Link>;
335335
```
336336

337+
A reader gets an entry's state in the same commit as that entry's page. While a navigation is pending (its loader still streaming, a `transition()` holding the page), the content on screen keeps the state of the entry being left, including for a reader that mounts during the wait; back/forward restores an entry's state together with its page. Inside an optimistically presented `clientUrls()` destination the hook returns the state the navigation carries, before the server has answered. A navigation that carries no state re-renders no reader; a value keeps its identity when a navigation passes the reader's own value forward or a server action changes another slot.
338+
339+
One limit remains on back/forward (issue #1031): `usePathname()` and `useSearchParams()` change at the `popstate` event, before a restored page that has to be fetched commits, so for that window the page on screen reads the destination's URL from them and its own entry's state from `useLocationState`.
340+
337341
`useLocationState<T>()` with no definition reads plain, untyped state. The same `state` option exists on `router.push()` and `router.replace()`, typed `HistoryState`: typed entries in an array (`[ProductState(value)]`) or plain structured-clone-safe data (`PlainHistoryState`). An entry passed without the array (`state: ProductState(value)`), a definition passed without calling it (`state: [ProductState]`), or an array mixing entries with plain values is a compile error, and in development a runtime error for untyped callers.
338342

339343
Plain state is checked at the top level only: functions, symbols, `Promise`, `WeakMap`, `WeakSet`, and `unknown` values are rejected, and array, `Map`, and `Set` elements are checked the same way, but plain object members are not. A function or React element inside a plain object, or a top-level React element or DOM node, still compiles and throws `DataCloneError` when the history entry is written. A typed `createLocationState<T>()` definition checks `T` all the way down.
340344

341345
`createLocationState<T>()` rejects types that cannot survive `history.state`'s structured clone (functions, symbols, React/RSC content, `unknown` fields). The compile error names the failing field and the reason, for example `LocationStateUnsafe<"...", "items[].info.values">` for an `unknown` field inside each element of `items`.
342346

343-
`createLocationState<T>({ flash: true })` makes read-once flash state that clears after it is read, so back/forward will not show it again. Set it from the server with `redirect(url, { state: [...] })` or `ctx.setLocationState(...)`.
347+
`createLocationState<T>({ flash: true })` makes read-once flash state that is cleared from the history entry after it is read, so back/forward and a reload will not show it again. It stays on screen until the next navigation commits. Set it from the server with `redirect(url, { state: [...] })` or `ctx.setLocationState(...)`.
344348

345-
Static access: `.read()` returns a snapshot (`undefined` during SSR, so call it post-mount, not during the initial render). `.write()` and `.delete()` mutate `history.state` via `replaceState`, are client-only (they throw on the server), and do not trigger `useLocationState` re-renders. `.read(location)` reads the slot from any `{ state }` snapshot instead of the current entry, such as a `transition({ when })` context's `from` / `to`; it works without `window` and never clears flash state.
349+
Static access: `.read()` returns a snapshot (`undefined` during SSR, so call it post-mount, not during the initial render). `.write()` and `.delete()` mutate `history.state` via `replaceState`, are client-only (they throw on the server), and do not change what `useLocationState` readers show, mounted or mounting later: readers get the written value when the entry is next restored (back/forward to it, or a reload). `.read(location)` reads the slot from any `{ state }` snapshot instead of the current entry, such as a `transition({ when })` context's `from` / `to`; it works without `window` and never clears flash state.
346350

347351
### invalidateClientCache()
348352

‎packages/rangojs-router/CHANGELOG.md‎

Lines changed: 161 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,7 @@ export const CarriedProducts = createLocationState<Product[]>({
7070
```tsx
7171
const { data } = useLoader(ProductsLoader); // the page named by ?page
7272
const carried = useLocationState(CarriedProducts) ?? [];
73-
const carriedIds = new Set(carried.map((product) => product.id));
74-
const products = [
75-
...carried,
76-
...data.products.filter((product) => !carriedIds.has(product.id)),
77-
];
73+
const products = [...carried, ...data.products];
7874

7975
<Link
8076
to={`/products?page=${data.page + 1}`}
@@ -114,10 +110,6 @@ const products = [
114110
- It cannot be combined with `flash`: `createLocationState` throws in
115111
development, since flash state is removed at its first read and the option
116112
could only drop a message nobody has seen.
117-
- The `carriedIds` filter in the example works around a known ordering in the
118-
router, with or without the option: a navigation applies the destination
119-
entry's state to a mounted reader before the destination's loader data
120-
commits, so until it lands `carried` includes the page still on screen.
121113

122114
To test it, plain `renderRoute(routes, { locationState })` is the client
123115
navigation and `renderRoute(routes, { hydrate: true, locationState })` is the
@@ -131,6 +123,166 @@ any definition. The helper rejects a name that contains `~`.
131123
Definitions that do not set the option keep their key, and the client start-up
132124
writes nothing to `history.state` when no key carries the suffix.
133125

126+
### Fixed: `useLocationState` changes together with the page it belongs to, not before it ([#1029](https://github.com/rangojs/rango/issues/1029))
127+
128+
A `useLocationState` reader received the destination entry's state as soon as
129+
the router pushed the entry, before the destination's content was on screen.
130+
For as long as the navigation was held (a loader still streaming, a
131+
`transition()`), the page showed the new entry's state next to the old
132+
entry's data. A "load more" list was the visible case: `?page=N` loads a page
133+
through a loader and the items already on screen ride along as location state
134+
on the link, so after the click every item of the current page was listed
135+
twice until the next page landed, with React's duplicate-key warning in
136+
development. Back/forward had the same shape: the reader took the restored
137+
entry's state at the `popstate` event, before the restored page. A reader
138+
that mounted during the wait read the destination's state too.
139+
140+
A reader now sees an entry's location state only together with that entry's
141+
page. The router keeps the state of the entry on screen next to the page it
142+
renders and changes both in one React commit, so the rule holds for a reader
143+
that is mounted across the navigation and for one that mounts while it is
144+
pending.
145+
146+
```tsx
147+
const { data } = useLoader(ProductsLoader); // the page named by ?page
148+
const carried = useLocationState(CarriedProducts) ?? [];
149+
const products = [...carried, ...data.products]; // no item twice, at any point
150+
```
151+
152+
State on the navigation means `<Link state>`, `router.push()` / `.replace()`
153+
with `state`, and what the server adds to it (`ctx.setLocationState()`,
154+
`redirect(url, { state })`).
155+
156+
| What changes the entry's state | A reader got it | Now |
157+
| ------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
158+
| a navigation React commits in a transition: any same-route navigation, a `transition()` route, a held loader | when the entry was pushed: before the page, for as long as it was held | in the commit that shows the destination |
159+
| a navigation to another route that commits at once; an intercept (a modal over the page) | with the page | unchanged |
160+
| back/forward, entry in the client cache | around the restore, in a commit of its own | in the commit that restores the entry |
161+
| back/forward, entry refetched | at the `popstate` event, for the whole fetch | in the commit that shows the refetched entry |
162+
| a navigation the server answers with nothing to re-render | when the entry was pushed | with the new location: the page on screen is the entry's |
163+
| `router.push(url, { revalidate: false })` (no server fetch) | at once | unchanged: at once, with the new location |
164+
| a server action's `setLocationState` (no navigation) | when the response arrived | unchanged moment; added to what readers show (see below) |
165+
| `flash` state | shown, and cleared from history, at the moments above | shown with the destination, then cleared from history |
166+
| `Def.write()` / `Def.delete()` | a mounted reader: at the next row above; a reader mounted afterwards: at its mount | when the entry is next restored: back/forward to it, or a reload |
167+
| a `clientUrls()` destination presented before the server answers | the entry being left, until the server answered | the state the navigation carries, from its first render |
168+
| a navigation superseded or cancelled before it commits | nothing | unchanged: nothing |
169+
| a reader that mounts while a navigation is pending | the destination's state, in the page being left | the state of the page it mounts in |
170+
171+
`clientUrls()`: inside the optimistic branch (the destination and the group's
172+
client layouts) a reader gets the `state` the navigation carries on its first
173+
optimistic render, as `useParams` and `usePathname` describe the destination
174+
there. Before, it read the entry being left until the server answered, so a
175+
product page could not show the name its link carried while its loader
176+
streamed. Chrome outside the group, and content the navigation keeps on
177+
screen (a same-route navigation, a destination that suspends with no
178+
boundary), keep the committed entry's state until the canonical commit. State
179+
the server adds is not part of the optimistic entry and arrives with that
180+
commit. In the branch the value is the object the navigation passed; from the
181+
commit on it is the entry's copy, so an object-valued slot is a new, equal
182+
object at that point.
183+
184+
What an existing app can notice:
185+
186+
- **A reader in content that stays on screen no longer previews the next
187+
entry.** If a layout read `useLocationState` to show something about a
188+
navigation still in flight (the name of the product being opened, say), it
189+
now shows it when the destination commits. For the pending window use
190+
`useNavigation()` or `useLinkStatus()`, or read the state in the
191+
destination: a component that mounts with the destination, its `loading()`
192+
skeleton and an intercepted modal's skeleton included, reads its entry's
193+
state on its first render, as before.
194+
- **A reader that mounts after `Def.write()` / `Def.delete()` no longer sees
195+
the change.** Readers show the entry's state as it was committed, whenever
196+
they mount; the written value reaches them when the entry is restored
197+
(back/forward to it, a reload). Before, a reader mounted after the write
198+
read it. `Def.read()` returns it at once, as before: a component that
199+
writes a draft and re-mounts in the same visit should initialise from
200+
`Def.read()` in an effect, or keep the draft in state above the re-mount.
201+
- **A `flash` value is shown until the next navigation commits, by every
202+
reader.** Three differences. It is cleared from `history.state` after the
203+
destination commits, not when the entry is pushed. A reader that stays
204+
mounted across a later navigation (a banner in a layout) no longer keeps
205+
the message: an entry that carries no flash shows none; before, it kept it
206+
until it unmounted or a back/forward. And a reader that mounts or re-mounts
207+
later in the same visit gets the message too, where before only readers
208+
that rendered before the first clear did: an effect keyed on the value (a
209+
toast) runs again on a re-mount. A server action's state does not end a
210+
flash on screen.
211+
- **Every reader renders once when a navigation changes the entry's location
212+
state**, in the commit that renders the page, whether or not its own slot
213+
changed. A navigation that leaves the state as it was (no state before and
214+
after, the same primitive, the reader's own value passed back) renders
215+
none. An object-valued slot keeps its identity when the navigation carries
216+
the reader's value forward or a server action changes another slot, so
217+
effects and memoized children keyed on it do not run; before, a change to
218+
any slot handed readers of object-valued slots a new object.
219+
An equal object that is not the one the reader holds is still a new value.
220+
- **A server action's state is added to what readers show**; it no longer
221+
re-reads the entry. Before, the action's update also made readers pick up
222+
an earlier `Def.write()`.
223+
- **A reader outside the router's tree returns `undefined`.** The hook reads
224+
the entry its router has on screen (the provider every rango app renders
225+
under). Rendered with no provider, in a separate `createRoot` or bare in a
226+
unit test, there is no such entry; before, it read `history.state`. Use
227+
`Def.read()` there, or `renderRoute` in a test.
228+
- **The `__rsc_locationstate` window event is gone.** It was internal and
229+
undocumented; code that listened for it or dispatched it gets nothing.
230+
231+
Not changed, and still a limit: on back/forward, `usePathname()` and
232+
`useSearchParams()` change at the `popstate` event, before a restored page
233+
that has to be fetched commits
234+
([#1031](https://github.com/rangojs/rango/issues/1031)). For that window the
235+
page on screen reads the destination's URL from those hooks and its own
236+
entry's location state.
237+
238+
On hydration nothing changes: a reader with no stored state renders once, and
239+
one with state renders `undefined` and then the value.
240+
241+
In unit tests, `renderRoute` delivers location state the same way, so a
242+
component can be tested across a pending navigation. `router.navigate()` takes
243+
`state` and `replace` next to `loaders`: `state` pushes an entry carrying it,
244+
`replace: true` replaces the current one, and with neither history is left
245+
alone (`navigate(url)` and `navigate(url, { replace: false })` are the same
246+
call).
247+
248+
```tsx
249+
await router.navigate("/products?page=2", {
250+
state: [CarriedProducts(onScreen)],
251+
loaders: [[ProductsLoader, pending]], // a Promise the test resolves later
252+
});
253+
expect(getAllByRole("listitem")).toHaveLength(onScreen.length); // still page 1
254+
```
255+
256+
A `popstate` event on `window` is a back/forward onto the entry
257+
`history.state` holds (`history.replaceState(entry, "")` first): readers take
258+
that entry as it is. A test that dispatched `__rsc_locationstate` itself has
259+
to go through one of these instead, and a test that rendered a
260+
`useLocationState` component without `renderRoute` has to render it through
261+
`renderRoute`.
262+
263+
### Fixed: back/forward to an entry of the same route restores that entry's page after the history cache dropped it ([#1030](https://github.com/rangojs/rango/issues/1030))
264+
265+
Going back or forward to a history entry on the same route that differs only
266+
in its search params left the wrong page on screen once the entry was no
267+
longer in the client's history cache (20 entries by default). The URL and the entry's
268+
location state changed; the content stayed the page being left. A "load more"
269+
list (`?page=N`) longer than the cache showed it: Back to page 3 from page 24
270+
kept page 24's items under page 3's URL.
271+
272+
| Back to `?page=3` from `?page=24`, entry no longer cached | URL | Page on screen |
273+
| --------------------------------------------------------- | --------- | ------------------ |
274+
| Before | `?page=3` | page 24 |
275+
| Now | `?page=3` | page 3 (refetched) |
276+
277+
The refetch told the server the client was already on the target URL (the
278+
address bar has moved by the time a back/forward is handled), so the server
279+
found nothing to re-render. It is now told the page actually on screen. A
280+
cached entry, and an entry on a different route, restored correctly before
281+
and are unchanged. So did an entry whose page the app had prefetched within
282+
`prefetchCacheTTL`: its return is served from the prefetch cache without
283+
asking the server, so with link prefetching on the wrong page showed only
284+
once that had expired. Nothing to adopt.
285+
134286
### Fixed: `useLocationState` no longer causes a hydration mismatch when its reader hydrates inside `<Suspense>` ([#1017](https://github.com/rangojs/rango/pull/1017))
135287

136288
After a reload or a back/forward navigation, `history.state` still holds the

0 commit comments

Comments
 (0)