Skip to content

Commit 707ecef

Browse files
authored
Wire up support for unstable_useTransitions flag (#14524)
1 parent b882394 commit 707ecef

File tree

15 files changed

+2413
-224
lines changed

15 files changed

+2413
-224
lines changed

.changeset/olive-planets-think.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
"react-router": patch
3+
---
4+
5+
Add new `unstable_useTransitions` flag to routers to give users control over the usage of [`React.startTransition`](https://react.dev/reference/react/startTransition) and [`React.useOptimistic`](https://react.dev/reference/react/useOptimistic).
6+
7+
- Framework Mode + Data Mode:
8+
- `<HydratedRouter unstable_transition>`/`<RouterProvider unstable_transition>`
9+
- When left unset (current default behavior)
10+
- Router state updates are wrapped in `React.startTransition`
11+
- ⚠️ This can lead to buggy behaviors if you are wrapping your own navigations/fetchers in `React.startTransition`
12+
- You should set the flag to `true` if you run into this scenario to get the enhanced `useOptimistic` behavior (requires React 19)
13+
- When set to `true`
14+
- Router state updates remain wrapped in `React.startTransition` (as they are without the flag)
15+
- `Link`/`Form` navigations will be wrapped in `React.startTransition`
16+
- A subset of router state info will be surfaced to the UI _during_ navigations via `React.useOptimistic` (i.e., `useNavigation()`, `useFetchers()`, etc.)
17+
- ⚠️ This is a React 19 API so you must also be React 19 to opt into this flag for Framework/Data Mode
18+
- When set to `false`
19+
- The router will not leverage `React.startTransition` or `React.useOptimistic` on any navigations or state changes
20+
- Declarative Mode
21+
- `<BrowserRouter unstable_useTransitions>`
22+
- When left unset
23+
- Router state updates are wrapped in `React.startTransition`
24+
- When set to `true`
25+
- Router state updates remain wrapped in `React.startTransition` (as they are without the flag)
26+
- `Link`/`Form` navigations will be wrapped in `React.startTransition`
27+
- When set to `false`
28+
- the router will not leverage `React.startTransition` on any navigations or state changes

.changeset/real-chairs-exercise.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router": patch
3+
---
4+
5+
Fix the promise returned from `useNavigate` in Framework/Data Mode so that it properly tracks the duration of `popstate` navigations (i.e., `navigate(-1)`)
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
---
2+
title: React Transitions
3+
unstable: true
4+
---
5+
6+
# React Transitions
7+
8+
[MODES: framework, data, declarative]
9+
10+
<br/>
11+
<br/>
12+
13+
[React 18][react-18] Introduced the concept of "transitions" which allow you differentiate urgent from non-urgent UI updates. We won't try to explain transitions or the underlying "concurrent rendering" concept in this doc, but you can read up on those concepts here:
14+
15+
- [What is Concurrent React][concurrent]
16+
- [Transitions][transitions]
17+
- [`React.useTransition`][use-transition]
18+
- [`React.startTransition`][start-transition]
19+
20+
[React 19][react-19] continued enhancing the async/concurrent landscape and introduces [actions][actions] and support for using async functions in transitions. With the support for async transitions, a new [`React.useOptimistic][use-optimistic-blog] [hook][use-optimistic] was introduced that allows you to surface state updates during a transition to show users instant feedback.
21+
22+
## Transitions in React Router
23+
24+
The introduction of transitions in React makes the story of how React Router manages your navigations and router state a bit more complicated. These are powerful APIs but they don't come without some nuance and added complexity. We aim to make React Router work seamlessly with the new React features, but in some cases there may exist some tension between the new React ways to do things and some patterns you are already using in your React Router apps (i.e., pending states, optimistic UI).
25+
26+
To ensure a smooth adoption story, we've introduced changes related to transitions behind an opt-in `unstable_useTransitions` flag so that you can upgrade in a non-breaking fashion.
27+
28+
### Current Behavior
29+
30+
Back in early 2023, Dan Abramov filed an [issue][dan-issue] for Remix v1 to use `React.startTransition` to "Remix router would be more Suspense-y". After a bit of clarification we [implemented][startTransition-pr] and shipped that in React Router [6.13.0][rr-6-13-0] via behind a `future.v7_startTransition` flag. In v7, that became the default behavior and all router state updates are currently wrapped in `React.startTransition`.
31+
32+
This turns out to be potentially problematic behavior today for 2 reasons:
33+
34+
- There are some valid use cases where you _don't_ want your updates wrapped in `startTransition`
35+
- One specific issue is that `React.useSyncExternalStore` is incompatible with transitions ([^1][uses-transition-issue], [^2][uses-transition-tweet]) so if you are using that in your application, you can run into tearing issues when combined with `React.startTransition`
36+
- React Router has a `flushSync` option on navigations to use [`React.flushSync`][flush-sync] for the state updates instead, but that's not always the proper solution
37+
- React 19 has added a new `startTransition(() => Promise))` API as well as a new `useOptimistic` hook to surface updates during transitions
38+
- Without some updates to React Router, `startTransition(() => navigate(path))` doesn't work as you might expect, because we are not using `useOptimistic` internally so router state updates don't surface during the navigation, which breaks hooks like `useNavigation`
39+
40+
To provide a solution to both of the above issues, we're introducing a new `unstable_useTransitions` prop for the router components that will let you opt-out of using `startTransition` for router state upodates (solving the first issue), or opt-into a more enhanced usage of `startTransition` + `useOptimistic` (solving the second issue). Because the current behavior is a bit incomplete with the new React 19 APIs, we plan to make the opt-in behavior the default in React Router v8, but we will likely retain the opt-out flag for use cases such as `useSyncExternalStore`.
41+
42+
### Opt-out via `unstable_useTransitions=false`
43+
44+
If your application is not "transition-friendly" due to the usage of `useSyncExternalStore` (or other reasons), then you can opt-out via the prop:
45+
46+
```tsx
47+
// Framework Mode (entry.client.tsx)
48+
<HydratedRouter unstable_useTransitions={false} />
49+
50+
// Data Mode
51+
<RouterProvider unstable_useTransitions={false} />
52+
53+
// Declarative Mode
54+
<BrowserRouter unstable_useTransitions={false} />
55+
```
56+
57+
This will stop the router from wrapping internal state updates in `startTransition`.
58+
59+
<docs-warning>We do not recommend this as a long-term solution because opting out of transitions means that your application will not be fully compatible with the modern features of React, including `Suspense`, `use`, `startTransition`, `useOptimistic`, `<ViewTransition>`, etc.</docs-warning>
60+
61+
### Opt-in via `unstable_useTransitions=true`
62+
63+
<docs-info>Opting into this feature in Framework or Data Mode requires that you are using React 19 because it needs access to [`React.useOptimistic`][use-optimistic]</docs-info>
64+
65+
If you want to make your application play nicely with all of the new React 19 features that rely on concurrent mode and transitions, then you can opt-in via the new prop:
66+
67+
```tsx
68+
// Framework Mode (entry.client.tsx)
69+
<HydratedRouter unstable_useTransitions />
70+
71+
// Data Mode
72+
<RouterProvider unstable_useTransitions />
73+
74+
// Declarative Mode
75+
<BrowserRouter unstable_useTransitions />
76+
```
77+
78+
With this flag enabled:
79+
80+
- All internal state updates are wrapped in `React.startTransition` (current behavior without the flag)
81+
- All `<Link>`/`<Form>` navigations will be wrapped in `React.startTransition`, using the promise returned by `useNavigate`/`useSubmit` so that the transition lasts for the duration of the navigation
82+
- `useNavigate`/`useSubmit` do not automatically wrap in `React.startTransition`, so you can opt-out of a transition-enabled navigation by using those directly
83+
- In Framework/Data modes, a subset of the router state updates during a navigation will be surfaced to the UI via `useOptimistic`
84+
- State related to the _ongoing_ navigation and all fetcher information will be surfaced:
85+
- `state.navigation` for `useNavigation()`
86+
- `state.revalidation` for `useRevalidator()`
87+
- `state.actionData` for `useActionData()`
88+
- `state.fetchers` for `useFetcher()` and `useFetchers()`
89+
- State related to the _current_ location will not be surfaced:
90+
- `state.location` for `useLocation`
91+
- `state.matches` for `useMatches()`,
92+
- `state.loaderData` for `useLoaderData()`
93+
- `state.errors` for `useRouteError()`
94+
- etc.
95+
96+
Enabling this flag means that you can now have fully-transition-enabled navigations that play nicely with any other ongoing transition-enabled aspects of your application.
97+
98+
The only APIs that are automatically wrapped in an async transition are `<Link>` and `<Form>`. For everything else, you need to wrap the operation in `startTransition` yourself.
99+
100+
```tsx
101+
// Automatically transition-enabled
102+
<Link to="/path" />
103+
<Form method="post" action="/path" />
104+
105+
// Manually transition-enabled
106+
startTransition(() => navigate("/path"));
107+
startTransition(() => submit(data, { method: 'post', action: "/path" }));
108+
startTransition(() => fetcher.load("/path"));
109+
startTransition(() => fetcher.submit(data, { method: "post", action: "/path" }));
110+
111+
// Not transition-enabled
112+
navigate("/path");
113+
submit(data, { method: 'post', action: "/path" });
114+
fetcher.load("/path");
115+
fetcher.submit(data, { method: "post", action: "/path" });
116+
```
117+
118+
**Important:** You must always `return` or `await` the `navigate` promise inside `startTransition` so that the transition encompasses the full duration of the navigation. If you forget to `return` or `await` the promise, the transition will end prematurely and things won't work as expected.
119+
120+
```tsx
121+
// ✅ Returned promise
122+
startTransition(() => navigate("/path"));
123+
startTransition(() => {
124+
setOptimistic(something);
125+
return navigate("/path"));
126+
});
127+
128+
// ✅ Awaited promise
129+
startTransition(async () => {
130+
setOptimistic(something);
131+
await navigate("/path"));
132+
});
133+
134+
// ❌ Non-returned promise
135+
startTransition(() => {
136+
setOptimistic(something);
137+
navigate("/path"));
138+
});
139+
140+
// ❌ Non-Awaited promise
141+
startTransition(async () => {
142+
setOptimistic(something);
143+
navigate("/path"));
144+
});
145+
```
146+
147+
#### `popstate` navigations
148+
149+
Due to limitations in React itself, [`popstate`][popstate] navigations cannot be transition-enabled. Any state updates during a `popstate` event are [automatically][popstate-sync-pr] [flushed][bsky-ricky-popstate] synchronously so that the browser can properly restore scroll position and form data.
150+
151+
However, the browser can only do this if the navigation is instant. If React Router needs to run loaders on a back navigation, the browser will not be able to restore scroll position or form data ([`<ScrollRestoration>`][scroll-restoration] can handle scroll position for you).
152+
153+
It is therefore not recommended to wrap `navigate(n)` navigations in `React.startTransition`
154+
unless you can manage your pending UI with local transition state (`React.useTransition`).
155+
156+
```tsx
157+
// ❌ This won't work correctly
158+
startTransition(() => navigate(-1));
159+
```
160+
161+
If you _need_ programmatic back-navigations to be transition-friendly in your app, you can introduce a small hack to prevent React from detecting the event and letting the transition work as expected. React checks `window.event` to determine if the state updates are part of a `popstate` event, so if you clear that out in your own listener you can trick React into treating it like any other state update:
162+
163+
```tsx
164+
// Add this to the top of your browser entry file
165+
window.addEventListener(
166+
"popstate",
167+
() => {
168+
window.event = null;
169+
},
170+
{
171+
capture: true,
172+
},
173+
);
174+
```
175+
176+
<docs-warning>Please be aware this is a hack, has not been thoroughly tested, and may not continue to work if React changes their underlying implementation. We did get their [permission][ricky-bsky-event-hack] to mention it though 😉</docs-warning>
177+
178+
[react-18]: https://react.dev/blog/2022/03/29/react-v18
179+
[concurrent]: https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react
180+
[transitions]: https://react.dev/blog/2022/03/29/react-v18#new-feature-transitions
181+
[use-transition]: https://react.dev/reference/react/useTransition#reference
182+
[start-transition]: https://react.dev/reference/react/startTransition
183+
[react-19]: https://react.dev/blog/2024/12/05/react-19
184+
[actions]: https://react.dev/blog/2024/12/05/react-19#actions
185+
[use-optimistic-blog]: https://react.dev/blog/2024/12/05/react-19#new-hook-optimistic-updates
186+
[use-optimistic]: https://react.dev/reference/react/useOptimistic
187+
[flush-sync]: https://react.dev/reference/react-dom/flushSync
188+
[dan-issue]: https://github.com/remix-run/remix/issues/5763
189+
[startTransition-pr]: https://github.com/remix-run/react-router/pull/10438
190+
[rr-6-13-0]: https://github.com/remix-run/react-router/blob/main/CHANGELOG.md#v6130
191+
[uses-transition-issue]: https://github.com/facebook/react/issues/26382
192+
[uses-transition-tweet]: https://x.com/rickhanlonii/status/1683636856808775682
193+
[bsky-ricky-popstate]: https://bsky.app/profile/ricky.fm/post/3m5ujj6tuks2e
194+
[popstate-sync-pr]: https://github.com/facebook/react/pull/26025
195+
[scroll-restoration]: ../api/components/ScrollRestoration
196+
[ricky-bsky-event-hack]: https://bsky.app/profile/ricky.fm/post/3m5wgqw3swc26
197+
[popstate]: https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event

packages/react-router/__tests__/data-memory-router-test.tsx

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,62 @@ describe("createMemoryRouter", () => {
10671067
]);
10681068
});
10691069

1070+
it("exposes promise from useNavigate (popstate)", async () => {
1071+
let sequence: string[] = [];
1072+
let router = createMemoryRouter(
1073+
[
1074+
{
1075+
path: "/",
1076+
async loader() {
1077+
sequence.push("loader start");
1078+
await new Promise((r) => setTimeout(r, 100));
1079+
sequence.push("loader end");
1080+
return null;
1081+
},
1082+
Component() {
1083+
sequence.push("render");
1084+
return <h1>Home</h1>;
1085+
},
1086+
},
1087+
{
1088+
path: "/page",
1089+
Component: () => {
1090+
let navigate = useNavigate();
1091+
return (
1092+
<>
1093+
<h1>Page</h1>
1094+
<button
1095+
onClick={async () => {
1096+
sequence.push("call navigate");
1097+
await navigate(-1);
1098+
sequence.push("navigate resolved");
1099+
}}
1100+
>
1101+
Back
1102+
</button>
1103+
</>
1104+
);
1105+
},
1106+
},
1107+
],
1108+
{ initialEntries: ["/", "/page"] },
1109+
);
1110+
1111+
let { container } = render(<RouterProvider router={router} />);
1112+
1113+
expect(getHtml(container)).toContain("Page");
1114+
fireEvent.click(screen.getByText("Back"));
1115+
await waitFor(() => screen.getByText("Home"));
1116+
1117+
expect(sequence).toEqual([
1118+
"call navigate",
1119+
"loader start",
1120+
"loader end",
1121+
"navigate resolved",
1122+
"render",
1123+
]);
1124+
});
1125+
10701126
it("exposes promise from useSubmit", async () => {
10711127
let sequence: string[] = [];
10721128
let router = createMemoryRouter([

packages/react-router/__tests__/dom/data-browser-router-test.tsx

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2527,6 +2527,75 @@ function testDomRouter(
25272527
`);
25282528
});
25292529

2530+
it("exposes promise from useNavigate (popstate)", async () => {
2531+
let sequence: string[] = [];
2532+
let router = createTestRouter(
2533+
[
2534+
{
2535+
id: "home",
2536+
path: "/",
2537+
async loader() {
2538+
sequence.push("loader start");
2539+
await new Promise((r) => setTimeout(r, 100));
2540+
sequence.push("loader end");
2541+
return null;
2542+
},
2543+
Component() {
2544+
sequence.push("render");
2545+
return (
2546+
<>
2547+
<h1>Home</h1>
2548+
<Link to="/page">Go to page</Link>
2549+
</>
2550+
);
2551+
},
2552+
},
2553+
{
2554+
path: "/page",
2555+
Component: () => {
2556+
let navigate = useNavigate();
2557+
return (
2558+
<>
2559+
<h1>Page</h1>
2560+
<button
2561+
onClick={async () => {
2562+
sequence.push("call navigate");
2563+
await navigate(-1);
2564+
sequence.push("navigate resolved");
2565+
}}
2566+
>
2567+
Back
2568+
</button>
2569+
</>
2570+
);
2571+
},
2572+
},
2573+
],
2574+
{
2575+
hydrationData: { loaderData: { home: null } },
2576+
window: getWindow("/"),
2577+
},
2578+
);
2579+
2580+
let { container } = render(<RouterProvider router={router} />);
2581+
2582+
expect(getHtml(container)).toContain("Home");
2583+
fireEvent.click(screen.getByText("Go to page"));
2584+
await waitFor(() => screen.getByText("Page"));
2585+
sequence.splice(0); // clear sequence
2586+
2587+
fireEvent.click(screen.getByText("Back"));
2588+
await waitFor(() => screen.getByText("Home"));
2589+
2590+
expect(sequence).toEqual([
2591+
"call navigate",
2592+
"loader start",
2593+
"loader end",
2594+
"navigate resolved",
2595+
"render",
2596+
]);
2597+
});
2598+
25302599
describe("<Form action>", () => {
25312600
function NoActionComponent() {
25322601
return (

0 commit comments

Comments
 (0)