useTransition·续1
Because the parent component updates its state inside the action, that state update gets marked as a Transition. This means you can click on "Posts" and then immediately click "Contact" and it does not block user interactions:
import { useState } from 'react';
import TabButton from './TabButton.js';
import AboutTab from './AboutTab.js';
import PostsTab from './PostsTab.js';
import ContactTab from './ContactTab.js';
export default function TabContainer() {
const [tab, setTab] = useState('about');
return (
<>
<TabButton
isActive={tab === 'about'}
action={() => setTab('about')}
>
About
</TabButton>
<TabButton
isActive={tab === 'posts'}
action={() => setTab('posts')}
>
Posts (slow)
</TabButton>
<TabButton
isActive={tab === 'contact'}
action={() => setTab('contact')}
>
Contact
</TabButton>
<hr />
{tab === 'about' && <AboutTab />}
{tab === 'posts' && <PostsTab />}
{tab === 'contact' && <ContactTab />}
</>
);
}
```js src/TabButton.js active import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) { const [isPending, startTransition] = useTransition(); if (isActive) { return {children} } if (isPending) { return {children}; } return ( ); }
```js src/AboutTab.js
export default function AboutTab() {
return (
<p>Welcome to my profile!</p>
);
}
```js {expectedErrors: {'react-compiler': [19, 20]}} src/PostsTab.js import { memo } from 'react';
const PostsTab = memo(function PostsTab() {
// Log once. The actual slowdown is inside SlowPost.
console.log('[ARTIFICIALLY SLOW] Rendering 500
let items = [];
for (let i = 0; i < 500; i++) {
items.push(
-
{items}
function SlowPost({ index }) { let startTime = performance.now(); while (performance.now() - startTime < 1) { // Do nothing for 1 ms per item to emulate extremely slow code }
return (
export default PostsTab;
```js src/ContactTab.js
export default function ContactTab() {
return (
<>
<p>
You can find me online here:
</p>
<ul>
<li>admin@mysite.com</li>
<li>+123456789</li>
</ul>
</>
);
}
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
.items {
max-height: 300px;
overflow: auto;
}
[!NOTE]
When exposing an
actionprop from a component, you shouldawaitit inside the transition.This allows the
actioncallback to be either synchronous or asynchronous without requiring an additionalstartTransitionto wrap theawaitin the action.
Displaying a pending visual state
You can use the isPending boolean value returned by useTransition to indicate to the user that a Transition is in progress. For example, the tab button can have a special "pending" visual state:
```js {4-6} function TabButton({ action, children, isActive }) { const [isPending, startTransition] = useTransition(); // ... if (isPending) { return {children}; } // ...
Notice how clicking "Posts" now feels more responsive because the tab button itself updates right away:
```js
import { useState } from 'react';
import TabButton from './TabButton.js';
import AboutTab from './AboutTab.js';
import PostsTab from './PostsTab.js';
import ContactTab from './ContactTab.js';
export default function TabContainer() {
const [tab, setTab] = useState('about');
return (
<>
<TabButton
isActive={tab === 'about'}
action={() => setTab('about')}
>
About
</TabButton>
<TabButton
isActive={tab === 'posts'}
action={() => setTab('posts')}
>
Posts (slow)
</TabButton>
<TabButton
isActive={tab === 'contact'}
action={() => setTab('contact')}
>
Contact
</TabButton>
<hr />
{tab === 'about' && <AboutTab />}
{tab === 'posts' && <PostsTab />}
{tab === 'contact' && <ContactTab />}
</>
);
}
```js src/TabButton.js active import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) { const [isPending, startTransition] = useTransition(); if (isActive) { return {children} } if (isPending) { return {children}; } return ( ); }
```js src/AboutTab.js
export default function AboutTab() {
return (
<p>Welcome to my profile!</p>
);
}
```js {expectedErrors: {'react-compiler': [19, 20]}} src/PostsTab.js import { memo } from 'react';
const PostsTab = memo(function PostsTab() {
// Log once. The actual slowdown is inside SlowPost.
console.log('[ARTIFICIALLY SLOW] Rendering 500
let items = [];
for (let i = 0; i < 500; i++) {
items.push(
-
{items}
function SlowPost({ index }) { let startTime = performance.now(); while (performance.now() - startTime < 1) { // Do nothing for 1 ms per item to emulate extremely slow code }
return (
export default PostsTab;
```js src/ContactTab.js
export default function ContactTab() {
return (
<>
<p>
You can find me online here:
</p>
<ul>
<li>admin@mysite.com</li>
<li>+123456789</li>
</ul>
</>
);
}
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
.items {
max-height: 300px;
overflow: auto;
}
Preventing unwanted loading indicators
In this example, the PostsTab component fetches some data using use. When you click the "Posts" tab, the PostsTab component suspends, causing the closest loading fallback to appear:
import { Suspense, useState } from 'react';
import TabButton from './TabButton.js';
import AboutTab from './AboutTab.js';
import PostsTab from './PostsTab.js';
import ContactTab from './ContactTab.js';
export default function TabContainer() {
const [tab, setTab] = useState('about');
return (
<Suspense fallback={<h1>🌀 Loading...</h1>}>
<TabButton
isActive={tab === 'about'}
action={() => setTab('about')}
>
About
</TabButton>
<TabButton
isActive={tab === 'posts'}
action={() => setTab('posts')}
>
Posts
</TabButton>
<TabButton
isActive={tab === 'contact'}
action={() => setTab('contact')}
>
Contact
</TabButton>
<hr />
{tab === 'about' && <AboutTab />}
{tab === 'posts' && <PostsTab />}
{tab === 'contact' && <ContactTab />}
</Suspense>
);
}
```js src/TabButton.js export default function TabButton({ action, children, isActive }) { if (isActive) { return {children} } return ( ); }
```js src/AboutTab.js hidden
export default function AboutTab() {
return (
<p>Welcome to my profile!</p>
);
}
```js src/PostsTab.js hidden import {use} from 'react'; import { fetchData } from './data.js';
function PostsTab() { const posts = use(fetchData('/posts')); return (
-
{posts.map(post =>
function Post({ title }) { return (
export default PostsTab;
```js src/ContactTab.js hidden
export default function ContactTab() {
return (
<>
<p>
You can find me online here:
</p>
<ul>
<li>admin@mysite.com</li>
<li>+123456789</li>
</ul>
</>
);
}
```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.startsWith('/posts')) { return await getPosts(); } else { throw Error('Not implemented'); } }
async function getPosts() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 1000); }); let posts = []; for (let i = 0; i < 500; i++) { posts.push({ id: i, title: 'Post #' + (i + 1) }); } return posts; }
```css
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
Hiding the entire tab container to show a loading indicator leads to a jarring user experience. If you add useTransition to TabButton, you can instead display the pending state in the tab button instead.
Notice that clicking "Posts" no longer replaces the entire tab container with a spinner:
import { Suspense, useState } from 'react';
import TabButton from './TabButton.js';
import AboutTab from './AboutTab.js';
import PostsTab from './PostsTab.js';
import ContactTab from './ContactTab.js';
export default function TabContainer() {
const [tab, setTab] = useState('about');
return (
<Suspense fallback={<h1>🌀 Loading...</h1>}>
<TabButton
isActive={tab === 'about'}
action={() => setTab('about')}
>
About
</TabButton>
<TabButton
isActive={tab === 'posts'}
action={() => setTab('posts')}
>
Posts
</TabButton>
<TabButton
isActive={tab === 'contact'}
action={() => setTab('contact')}
>
Contact
</TabButton>
<hr />
{tab === 'about' && <AboutTab />}
{tab === 'posts' && <PostsTab />}
{tab === 'contact' && <ContactTab />}
</Suspense>
);
}
```js src/TabButton.js active import { useTransition } from 'react';
export default function TabButton({ action, children, isActive }) { const [isPending, startTransition] = useTransition(); if (isActive) { return {children} } if (isPending) { return {children}; } return ( ); }
```js src/AboutTab.js hidden
export default function AboutTab() {
return (
<p>Welcome to my profile!</p>
);
}
```js src/PostsTab.js hidden import {use} from 'react'; import { fetchData } from './data.js';
function PostsTab() { const posts = use(fetchData('/posts')); return (
-
{posts.map(post =>
function Post({ title }) { return (
export default PostsTab;
```js src/ContactTab.js hidden
export default function ContactTab() {
return (
<>
<p>
You can find me online here:
</p>
<ul>
<li>admin@mysite.com</li>
<li>+123456789</li>
</ul>
</>
);
}
```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.startsWith('/posts')) { return await getPosts(); } else { throw Error('Not implemented'); } }
async function getPosts() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 1000); }); let posts = []; for (let i = 0; i < 500; i++) { posts.push({ id: i, title: 'Post #' + (i + 1) }); } return posts; }
```css
button { margin-right: 10px }
b { display: inline-block; margin-right: 10px; }
.pending { color: #777; }
Read more about using Transitions with Suspense.
[!NOTE]
Transitions only "wait" long enough to avoid hiding already revealed content (like the tab container). If the Posts tab had a nested
<Suspense>boundary, the Transition would not "wait" for it.
Building a Suspense-enabled router
If you're building a React framework or a router, we recommend marking page navigations as Transitions.
```js {3,6,8} function Router() { const [page, setPage] = useState('/'); const [isPending, startTransition] = useTransition();
function navigate(url) { startTransition(() => { setPage(url); }); } // ...
This is recommended for three reasons:
- [Transitions are interruptible,](#perform-non-blocking-updates-with-actions) which lets the user click away without waiting for the re-render to complete.
- [Transitions prevent unwanted loading indicators,](#preventing-unwanted-loading-indicators) which lets the user avoid jarring jumps on navigation.
- [Transitions wait for all pending actions](#perform-non-blocking-updates-with-actions) which lets the user wait for side effects to complete before the new page is shown.
Here is a simplified router example using Transitions for navigations.
```js src/App.js
import { Suspense, useState, useTransition } from 'react';
import IndexPage from './IndexPage.js';
import ArtistPage from './ArtistPage.js';
import Layout from './Layout.js';
export default function App() {
return (
<Suspense fallback={<BigSpinner />}>
<Router />
</Suspense>
);
}
function Router() {
const [page, setPage] = useState('/');
const [isPending, startTransition] = useTransition();
function navigate(url) {
startTransition(() => {
setPage(url);
});
}
let content;
if (page === '/') {
content = (
<IndexPage navigate={navigate} />
);
} else if (page === '/the-beatles') {
content = (
<ArtistPage
artist={{
id: 'the-beatles',
name: 'The Beatles',
}}
/>
);
}
return (
<Layout isPending={isPending}>
{content}
</Layout>
);
}
function BigSpinner() {
return <h2>🌀 Loading...</h2>;
}
```js src/Layout.js export default function Layout({ children, isPending }) { return (
```js src/IndexPage.js
export default function IndexPage({ navigate }) {
return (
<button onClick={() => navigate('/the-beatles')}>
Open The Beatles artist page
</button>
);
}
```js src/ArtistPage.js import { Suspense } from 'react'; import Albums from './Albums.js'; import Biography from './Biography.js'; import Panel from './Panel.js';
export default function ArtistPage({ artist }) { return ( <>
{artist.name}
function AlbumsGlimmer() { return (
```js src/Albums.js
import {use} from 'react';
import { fetchData } from './data.js';
export default function Albums({ artistId }) {
const albums = use(fetchData(`/${artistId}/albums`));
return (
<ul>
{albums.map(album => (
<li key={album.id}>
{album.title} ({album.year})
</li>
))}
</ul>
);
}
```js src/Biography.js import {use} from 'react'; import { fetchData } from './data.js';
export default function Biography({ artistId }) {
const bio = use(fetchData(/${artistId}/bio));
return (
{bio}
