UNPKG

8.72 kB Markdown View Raw
1---
2title: React Transitions
3---
4
5# React Transitions
6
7[MODES: framework, data, declarative]
8
9[React 18][react-18] introduced the concept of "transitions" which allow you to differentiate urgent from non-urgent UI updates. To learn more about React Transitions and "concurrent rendering" Please refer to React's official documentation:
10
11- [What is Concurrent React][concurrent]
12- [Transitions][transitions]
13- [`React.useTransition`][use-transition]
14- [`React.startTransition`][start-transition]
15
16[React 19][react-19] enhances the async/concurrent landscape by introducing [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 also introduced that allows you to surface state updates during a Transition to show users instant feedback.
17
18## Transitions in React Router
19
20The 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).
21
22To ensure a smooth adoption story, we've introduced changes related to Transitions behind an opt-in `useTransitions` flag so that you can upgrade in a non-breaking fashion.
23
24### Current Behavior
25
26We first leveraged `React.startTransition` to make React Router more Suspense-friendly in React Router [6.13.0][rr-6-13-0] via the `future.v7_startTransition` flag. In v7, that became the default behavior and all router state updates are currently wrapped in `React.startTransition`.
27
28This default behavior has 2 potential issues that `useTransitions` is designed to solve:
29
30- There are some valid use cases where you _don't_ want your updates wrapped in `startTransition`
31 - One specific issue is that `React.useSyncExternalStore` updates can't be Transitions ([^1][uses-transition-issue], [^2][uses-transition-tweet]). `useSyncExternalStore` forces a sync update, which means fallbacks can be shown in update transitions that would otherwise avoid showing the fallback.
32 - React Router has a `flushSync` option on navigations to use [`React.flushSync`][flush-sync] for state updates instead, but that's not always a proper solution
33- React 19 has added a new `startTransition(() => Promise))` API as well as a new `useOptimistic` hook to surface updates during Transitions
34 - 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`
35
36To provide a solution to both of the above issues, we're introducing a new `useTransitions` prop to the router components that will let you opt-out of using `startTransition` for router state updates (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`.
37
38### Opt-out via `useTransitions=false`
39
40If your application is not "Transition-friendly" due to the usage of `useSyncExternalStore` (or other reasons), then you can opt-out via the prop:
41
42```tsx
43// Framework Mode (entry.client.tsx)
44<HydratedRouter useTransitions={false} />
45
46// Data Mode
47<RouterProvider useTransitions={false} />
48
49// Declarative Mode
50<BrowserRouter useTransitions={false} />
51```
52
53This will stop the router from wrapping internal state updates in `startTransition`.
54
55### Opt-in via `useTransitions=true`
56
57<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>
58
59If 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:
60
61```tsx
62// Framework Mode (entry.client.tsx)
63<HydratedRouter useTransitions />
64
65// Data Mode
66<RouterProvider useTransitions />
67
68// Declarative Mode
69<BrowserRouter useTransitions />
70```
71
72With this flag enabled:
73
74- All internal state updates are wrapped in `React.startTransition` (current behavior without the flag)
75- 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
76 - `useNavigate`/`useSubmit` do not automatically wrap in `React.startTransition`, so you can opt-out of a Transition-enabled navigation by using those directly
77- In Framework/Data modes, a subset of the router state updates during a navigation will be surfaced to the UI via `useOptimistic`
78 - State related to the _ongoing_ navigation and all fetcher information will be surfaced:
79 - `state.navigation` for `useNavigation()`
80 - `state.revalidation` for `useRevalidator()`
81 - `state.actionData` for `useActionData()`
82 - `state.fetchers` for `useFetcher()` and `useFetchers()`
83 - State related to the _current_ location will not be surfaced:
84 - `state.location` for `useLocation`
85 - `state.matches` for `useMatches()`,
86 - `state.loaderData` for `useLoaderData()`
87 - `state.errors` for `useRouteError()`
88 - etc.
89
90Enabling 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.
91
92The 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.
93
94```tsx
95// Automatically Transition-enabled
96<Link to="/path" />
97<Form method="post" action="/path" />
98
99// Manually Transition-enabled
100startTransition(() => navigate("/path"));
101startTransition(() => submit(data, { method: 'post', action: "/path" }));
102startTransition(() => fetcher.load("/path"));
103startTransition(() => fetcher.submit(data, { method: "post", action: "/path" }));
104
105// Not Transition-enabled
106navigate("/path");
107submit(data, { method: 'post', action: "/path" });
108fetcher.load("/path");
109fetcher.submit(data, { method: "post", action: "/path" });
110```
111
112**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.
113
114```tsx
115// ✅ Returned promise
116startTransition(() => navigate("/path"));
117startTransition(() => {
118 setOptimistic(something);
119 return navigate("/path"));
120});
121
122// ✅ Awaited promise
123startTransition(async () => {
124 setOptimistic(something);
125 await navigate("/path"));
126});
127
128// ❌ Non-returned promise
129startTransition(() => {
130 setOptimistic(something);
131 navigate("/path"));
132});
133
134// ❌ Non-Awaited promise
135startTransition(async () => {
136 setOptimistic(something);
137 navigate("/path"));
138});
139```
140
141#### `popstate` navigations
142
143There is currently a bug with optimistic states and `popstate`. If you need to read the current route during a back navigation, which cannot complete synchronously (e.g. Suspends on uncached data), you can set the optimistic state before navigating back or defer the optimistic update in a timer or microtask.
144
145[react-18]: https://react.dev/blog/2022/03/29/react-v18
146[concurrent]: https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react
147[transitions]: https://react.dev/blog/2022/03/29/react-v18#new-feature-transitions
148[use-transition]: https://react.dev/reference/react/useTransition#reference
149[start-transition]: https://react.dev/reference/react/startTransition
150[react-19]: https://react.dev/blog/2024/12/05/react-19
151[actions]: https://react.dev/blog/2024/12/05/react-19#actions
152[use-optimistic-blog]: https://react.dev/blog/2024/12/05/react-19#new-hook-optimistic-updates
153[use-optimistic]: https://react.dev/reference/react/useOptimistic
154[flush-sync]: https://react.dev/reference/react-dom/flushSync
155[rr-6-13-0]: https://github.com/remix-run/react-router/blob/main/CHANGELOG.md#v6130
156[uses-transition-issue]: https://github.com/facebook/react/issues/26382
157[uses-transition-tweet]: https://x.com/rickhanlonii/status/1683636856808775682