|
| 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 |
0 commit comments