Switching topicsReact · 6 filesimport { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./styles.css";
createRoot(document.getElementById("root")).render(<App />);
// A pretend server. It logs each request, answers after a delay, and can't
// load topic 4, so you can see what happens when a request fails.
const topics = [
{ id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." },
{ id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." },
{ id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." },
{ id: 4, title: "Broken topic", summary: "" },
];
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function fetchTopicList() {
console.log("request: topic list");
await wait(400);
return topics.map(({ id, title }) => ({ id, title }));
}
export async function fetchTopic(id) {
console.log(`request: topic ${id}`);
await wait(id === 3 ? 1200 : 500);
if (id === 4) throw new Error("Topic 4 couldn't be loaded.");
return topics.find((topic) => topic.id === id);
}
import { Suspense, useState } from "react";
import TopicCard from "./TopicCard.jsx";
export default function App() {
const [id, setId] = useState(1);
return (
<main>
<h1>Study Hub</h1>
<div className="toolbar">
{[1, 2, 3].map((n) => (
<button key={n} aria-pressed={n === id} onClick={() => setId(n)}>
Topic {n}
</button>
))}
</div>
<Suspense fallback={<p className="muted">Loading topic…</p>}>
<TopicCard id={id} />
</Suspense>
</main>
);
}
import { fetchTopic, fetchTopicList } from "./api.js";
// One promise per request, reused on every render. use() needs this: a new
// promise each render would mean a new request each render.
const cache = new Map();
function cached(key, load) {
if (!cache.has(key)) cache.set(key, load());
return cache.get(key);
}
export const getTopicList = () => cached("topics", fetchTopicList);
export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id));
export function invalidate(key) {
cache.delete(key);
}
import { use } from "react";
import { getTopic } from "./cache.js";
export default function TopicCard({ id }) {
const topic = use(getTopic(id));
return (
<section className="panel">
<h2>{topic.title}</h2>
<p>{topic.summary}</p>
</section>
);
}
body {
font: 15px/1.5 system-ui, sans-serif;
margin: 0;
background: #f4f6f9;
color: #1c2430;
}
main {
max-width: 56rem;
margin: 1rem auto;
padding: 0 1rem;
}
h1 {
margin: 0 0 0.5rem;
font-size: 1.4rem;
}
input,
select,
button,
textarea {
font: inherit;
}
input,
select,
textarea {
padding: 0.3rem 0.5rem;
border: 1px solid #c4ccd6;
border-radius: 6px;
}
button {
padding: 0.25rem 0.7rem;
border: 1px solid #c4ccd6;
border-radius: 6px;
background: white;
cursor: pointer;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.75rem;
}
.board {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
}
.column {
background: #e9edf2;
border-radius: 10px;
padding: 0.6rem;
min-height: 6rem;
}
.column h2 {
margin: 0 0 0.5rem;
font-size: 0.95rem;
}
.count {
color: #5c6878;
font-weight: normal;
}
.cards {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.4rem;
}
.card {
background: white;
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.45rem 0.6rem;
}
.card button.title {
border: 0;
padding: 0;
background: none;
text-align: left;
font-weight: 600;
}
.card.selected {
outline: 2px solid #087ea4;
}
.muted {
color: #5c6878;
font-size: 0.85rem;
}
.panel {
margin-top: 0.75rem;
background: white;
border: 1px solid #d6dde6;
border-radius: 10px;
padding: 0.75rem 1rem;
}
.panel h2 {
margin: 0 0 0.25rem;
font-size: 1.05rem;
}
.error {
color: #b42318;
}
[role="tablist"] {
display: flex;
gap: 0.25rem;
border-bottom: 1px solid #d6dde6;
margin-bottom: 0.75rem;
}
[role="tab"] {
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: none;
padding: 0.4rem 0.8rem;
}
[role="tab"][aria-selected="true"] {
border-bottom-color: #087ea4;
color: #06617f;
font-weight: 600;
}
.stars button {
border: 0;
background: none;
padding: 0 0.1rem;
font-size: 1.3rem;
color: #b9c2cd;
}
.stars button[aria-checked="true"],
.stars button.on {
color: #d99a00;
}
Runs with Vite on your computer: unzip, then npm install and npm run dev.
What you'll see
Topic 1 disappears, Loading topic… shows for over a second, and then topic 3
appears. The content you were reading vanished before there was anything to
replace it with.
Transitions keep what's on screen
From the intermediate course: startTransition marks an update as non-urgent.
With Suspense, that has a useful effect. If a transition makes something
suspend, React keeps showing the current content instead of the fallback,
until the new content is ready. isPending says it's waiting.
JavaScript
import { Suspense, useState, useTransition } from "react";
Make the change and click Topic 3 again. Topic 1 fades and stays readable
until topic 3 replaces it.
When the fallback still shows
Transitions only keep content that's already on screen. The fallback still
shows when:
the boundary is showing for the first time, as on the first load;
the boundary is new. A different key on the boundary, or on anything
around it, makes a new boundary, which has nothing old to keep showing.
The second one is easy to trip over. An error boundary with
key={selectedId}, a common way to reset it, also gives the Suspense inside it
a new identity, and the fallback flashes again. The checkpoint shows a
boundary that resets with a resetKey prop instead.
Nested boundaries
Boundaries can nest. The outer one shows until the outer content is ready; the
inner ones then fill in as their own data arrives. Place them where waiting
makes sense to a reader: a whole page can show a skeleton, while one slow panel
inside it shows its own spinner.
Exercise
Say what's loading
While a transition is pending, show Loading topic 3… next to the buttons,
with the topic being loaded. Show nothing when idle.
Your working spaceReact · 6 filesimport { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./styles.css";
createRoot(document.getElementById("root")).render(<App />);
// A pretend server. It logs each request, answers after a delay, and can't
// load topic 4, so you can see what happens when a request fails.
const topics = [
{ id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." },
{ id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." },
{ id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." },
{ id: 4, title: "Broken topic", summary: "" },
];
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function fetchTopicList() {
console.log("request: topic list");
await wait(400);
return topics.map(({ id, title }) => ({ id, title }));
}
export async function fetchTopic(id) {
console.log(`request: topic ${id}`);
await wait(id === 3 ? 1200 : 500);
if (id === 4) throw new Error("Topic 4 couldn't be loaded.");
return topics.find((topic) => topic.id === id);
}
import { Suspense, useState } from "react";
import TopicCard from "./TopicCard.jsx";
export default function App() {
const [id, setId] = useState(1);
return (
<main>
<h1>Study Hub</h1>
<div className="toolbar">
{[1, 2, 3].map((n) => (
<button key={n} aria-pressed={n === id} onClick={() => setId(n)}>
Topic {n}
</button>
))}
</div>
<Suspense fallback={<p className="muted">Loading topic…</p>}>
<TopicCard id={id} />
</Suspense>
</main>
);
}
import { fetchTopic, fetchTopicList } from "./api.js";
// One promise per request, reused on every render. use() needs this: a new
// promise each render would mean a new request each render.
const cache = new Map();
function cached(key, load) {
if (!cache.has(key)) cache.set(key, load());
return cache.get(key);
}
export const getTopicList = () => cached("topics", fetchTopicList);
export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id));
export function invalidate(key) {
cache.delete(key);
}
import { use } from "react";
import { getTopic } from "./cache.js";
export default function TopicCard({ id }) {
const topic = use(getTopic(id));
return (
<section className="panel">
<h2>{topic.title}</h2>
<p>{topic.summary}</p>
</section>
);
}
body {
font: 15px/1.5 system-ui, sans-serif;
margin: 0;
background: #f4f6f9;
color: #1c2430;
}
main {
max-width: 56rem;
margin: 1rem auto;
padding: 0 1rem;
}
h1 {
margin: 0 0 0.5rem;
font-size: 1.4rem;
}
input,
select,
button,
textarea {
font: inherit;
}
input,
select,
textarea {
padding: 0.3rem 0.5rem;
border: 1px solid #c4ccd6;
border-radius: 6px;
}
button {
padding: 0.25rem 0.7rem;
border: 1px solid #c4ccd6;
border-radius: 6px;
background: white;
cursor: pointer;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
margin-bottom: 0.75rem;
}
.board {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.75rem;
}
.column {
background: #e9edf2;
border-radius: 10px;
padding: 0.6rem;
min-height: 6rem;
}
.column h2 {
margin: 0 0 0.5rem;
font-size: 0.95rem;
}
.count {
color: #5c6878;
font-weight: normal;
}
.cards {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.4rem;
}
.card {
background: white;
border: 1px solid #d6dde6;
border-radius: 8px;
padding: 0.45rem 0.6rem;
}
.card button.title {
border: 0;
padding: 0;
background: none;
text-align: left;
font-weight: 600;
}
.card.selected {
outline: 2px solid #087ea4;
}
.muted {
color: #5c6878;
font-size: 0.85rem;
}
.panel {
margin-top: 0.75rem;
background: white;
border: 1px solid #d6dde6;
border-radius: 10px;
padding: 0.75rem 1rem;
}
.panel h2 {
margin: 0 0 0.25rem;
font-size: 1.05rem;
}
.error {
color: #b42318;
}
[role="tablist"] {
display: flex;
gap: 0.25rem;
border-bottom: 1px solid #d6dde6;
margin-bottom: 0.75rem;
}
[role="tab"] {
border: 0;
border-bottom: 2px solid transparent;
border-radius: 0;
background: none;
padding: 0.4rem 0.8rem;
}
[role="tab"][aria-selected="true"] {
border-bottom-color: #087ea4;
color: #06617f;
font-weight: 600;
}
.stars button {
border: 0;
background: none;
padding: 0 0.1rem;
font-size: 1.3rem;
color: #b9c2cd;
}
.stars button[aria-checked="true"],
.stars button.on {
color: #d99a00;
}
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
The topic being requested and the topic still visible are different facts while a transition is pending.
Hint 2: a first step
Remember which topic was asked for in a second piece of state, set outside
the transition, so it updates straight away. Compare it with id.