useTransition·续2
```js src/Panel.js export default function Panel({ children }) { return (
```js src/data.js hidden
// Note: the way you would do data fetching depends on
// the framework that you use together with Suspense.
// Normally, the caching logic would be inside a framework.
let cache = new Map();
export function fetchData(url) {
if (!cache.has(url)) {
cache.set(url, getData(url));
}
return cache.get(url);
}
async function getData(url) {
if (url === '/the-beatles/albums') {
return await getAlbums();
} else if (url === '/the-beatles/bio') {
return await getBio();
} else {
throw Error('Not implemented');
}
}
async function getBio() {
// Add a fake delay to make waiting noticeable.
await new Promise(resolve => {
setTimeout(resolve, 500);
});
return `The Beatles were an English rock band,
formed in Liverpool in 1960, that comprised
John Lennon, Paul McCartney, George Harrison
and Ringo Starr.`;
}
async function getAlbums() {
// Add a fake delay to make waiting noticeable.
await new Promise(resolve => {
setTimeout(resolve, 3000);
});
return [{
id: 13,
title: 'Let It Be',
year: 1970
}, {
id: 12,
title: 'Abbey Road',
year: 1969
}, {
id: 11,
title: 'Yellow Submarine',
year: 1969
}, {
id: 10,
title: 'The Beatles',
year: 1968
}, {
id: 9,
title: 'Magical Mystery Tour',
year: 1967
}, {
id: 8,
title: 'Sgt. Pepper\'s Lonely Hearts Club Band',
year: 1967
}, {
id: 7,
title: 'Revolver',
year: 1966
}, {
id: 6,
title: 'Rubber Soul',
year: 1965
}, {
id: 5,
title: 'Help!',
year: 1965
}, {
id: 4,
title: 'Beatles For Sale',
year: 1964
}, {
id: 3,
title: 'A Hard Day\'s Night',
year: 1964
}, {
id: 2,
title: 'With The Beatles',
year: 1963
}, {
id: 1,
title: 'Please Please Me',
year: 1963
}];
}
main {
min-height: 200px;
padding: 10px;
}
.layout {
border: 1px solid black;
}
.header {
background: #222;
padding: 10px;
text-align: center;
color: white;
}
.bio { font-style: italic; }
.panel {
border: 1px solid #aaa;
border-radius: 6px;
margin-top: 20px;
padding: 10px;
}
.glimmer-panel {
border: 1px dashed #aaa;
background: linear-gradient(90deg, rgba(221,221,221,1) 0%, rgba(255,255,255,1) 100%);
border-radius: 6px;
margin-top: 20px;
padding: 10px;
}
.glimmer-line {
display: block;
width: 60%;
height: 20px;
margin: 10px;
border-radius: 4px;
background: #f0f0f0;
}
[!NOTE]
Suspense-enabled routers are expected to wrap the navigation updates into Transitions by default.
Displaying an error to users with an error boundary
If a function passed to startTransition throws an error or returns a rejected Promise, you can display an error to your user with an error boundary. To use an error boundary, wrap the component where you are calling the useTransition in an error boundary. Once the function passed to startTransition errors, the fallback for the error boundary will be displayed.
```js src/AddCommentContainer.js active import { useTransition } from "react"; import { ErrorBoundary } from "react-error-boundary";
export function AddCommentContainer() { return ( <ErrorBoundary fallback={
⚠️Something went wrong
}>function addComment(comment) { // For demonstration purposes to show Error Boundary if (comment == null) { throw new Error("Example Error: An error thrown to trigger error boundary"); } }
function AddCommentButton() { const [pending, startTransition] = useTransition();
return ( ); }
```js src/App.js hidden
import { AddCommentContainer } from "./AddCommentContainer.js";
export default function App() {
return <AddCommentContainer />;
}
```js src/index.js hidden import React, { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './styles.css'; import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(
```json package.json hidden
{
"dependencies": {
"react": "19.0.0-rc-3edc000d-20240926",
"react-dom": "19.0.0-rc-3edc000d-20240926",
"react-scripts": "^5.0.0",
"react-error-boundary": "4.0.3"
},
"main": "/index.js"
}
Troubleshooting
Updating an input in a Transition doesn't work
You can't use a Transition for a state variable that controls an input:
```js {4,10} const [text, setText] = useState(''); // ... function handleChange(e) { // ❌ Can't use Transitions for controlled input state startTransition(() => { setText(e.target.value); }); } // ... return ;
This is because Transitions are non-blocking, but updating an input in response to the change event should happen synchronously. If you want to run a Transition in response to typing, you have two options:
1. You can declare two separate state variables: one for the input state (which always updates synchronously), and one that you will update in a Transition. This lets you control the input using the synchronous state, and pass the Transition state variable (which will "lag behind" the input) to the rest of your rendering logic.
2. Alternatively, you can have one state variable, and add [`useDeferredValue`](/reference/react/useDeferredValue) which will "lag behind" the real value. It will trigger non-blocking re-renders to "catch up" with the new value automatically.
---
### React doesn't treat my state update as a Transition
When you wrap a state update in a Transition, make sure that it happens *during* the `startTransition` call:
```js
startTransition(() => {
// ✅ Setting state *during* startTransition call
setPage('/about');
});
The function you pass to startTransition must be synchronous. You can't mark an update as a Transition like this:
startTransition(() => {
// ❌ Setting state *after* startTransition call
setTimeout(() => {
setPage('/about');
}, 1000);
});
Instead, you could do this:
setTimeout(() => {
startTransition(() => {
// ✅ Setting state *during* startTransition call
setPage('/about');
});
}, 1000);
React doesn't treat my state update after await as a Transition
When you use await inside a startTransition function, the state updates that happen after the await are not marked as Transitions. You must wrap state updates after each await in a startTransition call:
startTransition(async () => {
await someAsyncFunction();
// ❌ Not using startTransition after await
setPage('/about');
});
However, this works instead:
startTransition(async () => {
await someAsyncFunction();
// ✅ Using startTransition *after* await
startTransition(() => {
setPage('/about');
});
});
This is a JavaScript limitation due to React losing the scope of the async context. In the future, when AsyncContext is available, this limitation will be removed.
I want to call useTransition from outside a component
You can't call useTransition outside a component because it's a Hook. In this
case, the standalone startTransition
function can mark state updates as Transitions. It does not provide the
isPending flag. Because the standalone function is not associated with a
component, an Error Boundary cannot handle errors from its Transition.
The function I pass to startTransition executes immediately
If you run this code, it will print 1, 2, 3:
```js {1,3,6} console.log(1); startTransition(() => { console.log(2); setPage('/about'); }); console.log(3);
**It is expected to print 1, 2, 3.** The function you pass to `startTransition` does not get delayed. Unlike with the browser `setTimeout`, it does not run the callback later. React executes your function immediately, but any state updates scheduled *while it is running* are marked as Transitions. You can imagine that it works like this:
```js
// A simplified version of how React works
let isInsideTransition = false;
function startTransition(scope) {
isInsideTransition = true;
scope();
isInsideTransition = false;
}
function setState() {
if (isInsideTransition) {
// ... schedule a Transition state update ...
} else {
// ... schedule an urgent state update ...
}
}
My state updates in Transitions are out of order
If you await inside startTransition, you might see the updates happen out of order.
In this example, the updateQuantity function simulates a request to the server to update the item's quantity in the cart. This function artificially returns every other request after the previous to simulate race conditions for network requests.
Try updating the quantity once, then update it quickly multiple times. You might see the incorrect total:
```json package.json hidden { "dependencies": { "react": "beta", "react-dom": "beta" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
```js src/App.js
import { useState, useTransition } from "react";
import { updateQuantity } from "./api";
import Item from "./Item";
import Total from "./Total";
export default function App({}) {
const [quantity, setQuantity] = useState(1);
const [isPending, startTransition] = useTransition();
// Store the actual quantity in separate state to show the mismatch.
const [clientQuantity, setClientQuantity] = useState(1);
const updateQuantityAction = newQuantity => {
setClientQuantity(newQuantity);
// Access the pending state of the transition,
// by wrapping in startTransition again.
startTransition(async () => {
const savedQuantity = await updateQuantity(newQuantity);
startTransition(() => {
setQuantity(savedQuantity);
});
});
};
return (
<div>
<h1>Checkout</h1>
<Item action={updateQuantityAction}/>
<hr />
<Total clientQuantity={clientQuantity} savedQuantity={quantity} isPending={isPending} />
</div>
);
}
```js src/Item.js import {startTransition} from 'react';
export default function Item({action}) { function handleChange(e) { // Update the quantity in an Action. startTransition(async () => { await action(e.target.value); }); } return (
```js src/Total.js
const intl = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
});
export default function Total({ clientQuantity, savedQuantity, isPending }) {
return (
<div className="total">
<span>Total:</span>
<div>
<div>
{isPending
? "🌀 Updating..."
: `${intl.format(savedQuantity * 9999)}`}
</div>
<div className="error">
{!isPending &&
clientQuantity !== savedQuantity &&
`Wrong total, expected: ${intl.format(clientQuantity * 9999)}`}
</div>
</div>
</div>
);
}
```js src/api.js let firstRequest = true; export async function updateQuantity(newName) { return new Promise((resolve, reject) => { if (firstRequest === true) { firstRequest = false; setTimeout(() => { firstRequest = true; resolve(newName); // Simulate every other request being slower }, 1000); } else { setTimeout(() => { resolve(newName); }, 50); } }); }
```css
.item {
display: flex;
align-items: center;
justify-content: start;
}
.item label {
flex: 1;
text-align: right;
}
.item input {
margin-left: 4px;
width: 60px;
padding: 4px;
}
.total {
height: 50px;
line-height: 25px;
display: flex;
align-content: center;
justify-content: space-between;
}
.total div {
display: flex;
flex-direction: column;
align-items: flex-end;
}
.error {
color: red;
}
When clicking multiple times, it's possible for previous requests to finish after later requests. When this happens, React currently has no way to know the intended order. This is because the updates are scheduled asynchronously, and React loses context of the order across the async boundary.
This is expected, because Actions within a Transition do not guarantee execution order. For common use cases, React provides higher-level abstractions like useActionState and <form> actions that handle ordering for you. For advanced use cases, you'll need to implement your own queuing and abort logic to handle this.
Example of useActionState handling execution order:
```json package.json hidden { "dependencies": { "react": "beta", "react-dom": "beta" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
```js src/App.js
import { useState, useActionState } from "react";
import { updateQuantity } from "./api";
import Item from "./Item";
import Total from "./Total";
export default function App({}) {
// Store the actual quantity in separate state to show the mismatch.
const [clientQuantity, setClientQuantity] = useState(1);
const [quantity, updateQuantityAction, isPending] = useActionState(
async (prevState, payload) => {
setClientQuantity(payload);
const savedQuantity = await updateQuantity(payload);
return savedQuantity; // Return the new quantity to update the state
},
1 // Initial quantity
);
return (
<div>
<h1>Checkout</h1>
<Item action={updateQuantityAction}/>
<hr />
<Total clientQuantity={clientQuantity} savedQuantity={quantity} isPending={isPending} />
</div>
);
}
```js src/Item.js import {startTransition} from 'react';
export default function Item({action}) { function handleChange(e) { // Update the quantity in an Action. startTransition(() => { action(e.target.value); }); } return (
```js src/Total.js
const intl = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
});
export default function Total({ clientQuantity, savedQuantity, isPending }) {
return (
<div className="total">
<span>Total:</span>
<div>
<div>
{isPending
? "🌀 Updating..."
: `${intl.format(savedQuantity * 9999)}`}
</div>
<div className="error">
{!isPending &&
clientQuantity !== savedQuantity &&
`Wrong total, expected: ${intl.format(clientQuantity * 9999)}`}
</div>
</div>
</div>
);
}
```js src/api.js let firstRequest = true; export async function updateQuantity(newName) { return new Promise((resolve, reject) => { if (firstRequest === true) { firstRequest = false; setTimeout(() => { firstRequest = true; resolve(newName); // Simulate every other request being slower }, 1000); } else { setTimeout(() => { resolve(newName); }, 50); } }); }
```css
.item {
display: flex;
align-items: center;
justify-content: start;
}
.item label {
flex: 1;
text-align: right;
}
.item input {
margin-left: 4px;
width: 60px;
padding: 4px;
}
.total {
height: 50px;
line-height: 25px;
display: flex;
align-content: center;
justify-content: space-between;
}
.total div {
display: flex;
flex-direction: column;
align-items: flex-end;
}
.error {
color: red;
}
