Skip to content

Checkpoint: A Topic Explorer

The Course
•
20 min study

Close the earlier lessons and build this from the brief. The starter has the pretend server, the cache, and an error boundary that takes a fallback(error, reset) function and a resetKey prop.

The brief

  • Load the topic list with use(getTopicList()), and show a button for each topic. While the list loads, show Loading topics….
  • Below the buttons, show the selected topic's title and summary with use(getTopic(id)), starting with topic 1.
  • Switching topics is a transition: the old topic stays, faded, until the new one is ready.
  • Hovering a button preloads its topic.
  • Broken topic can't load. Show its error with a Try again button that removes it from the cache and resets the boundary. Choosing another topic also clears the error.

Acceptance checks:

  • Clicking Transitions never shows Loading topic…; the old topic fades instead.
  • Broken topic shows Topic 4 couldn't be loaded. and Try again sends a new request.
  • After the error, clicking use shows that topic.
Your workspace React · 6 files
import { 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); } // Build the topic explorer here. api.js, cache.js and ErrorBoundary.jsx are // ready to use. See the brief. export default function App() { return ( <main> <h1>Topic explorer</h1> </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 { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } 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: where the boundaries go

One <Suspense> around everything, for the list. Inside it, around the topic details: the error boundary, then a second <Suspense>.

Hint 2: resetting without remounting

Give the error boundary resetKey={selectedId}, not key={selectedId}. A key would make a new Suspense boundary on every switch, and the fallback would flash.

Show one solution
One solution React · 6 files
import { 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, use, useState, useTransition } from "react"; import ErrorBoundary from "./ErrorBoundary.jsx"; import { getTopic, getTopicList, invalidate } from "./cache.js"; function TopicList({ selectedId, onSelect }) { const topics = use(getTopicList()); return ( <div className="toolbar"> {topics.map((topic) => ( <button key={topic.id} aria-pressed={topic.id === selectedId} onClick={() => onSelect(topic.id)} onMouseEnter={() => getTopic(topic.id).catch(() => {})}> {topic.title} </button> ))} </div> ); } function TopicDetails({ id }) { const topic = use(getTopic(id)); return ( <section className="panel"> <h2>{topic.title}</h2> <p>{topic.summary}</p> </section> ); } export default function App() { const [selectedId, setSelectedId] = useState(1); const [isPending, startTransition] = useTransition(); function select(id) { startTransition(() => setSelectedId(id)); } return ( <main> <h1>Topic explorer</h1> <Suspense fallback={<p className="muted">Loading topics…</p>}> <TopicList selectedId={selectedId} onSelect={select} /> <div style={{ opacity: isPending ? 0.5 : 1 }}> <ErrorBoundary resetKey={selectedId} fallback={(error, reset) => ( <p className="error"> {error.message}{" "} <button onClick={() => { invalidate(`topic:${selectedId}`); reset(); }}>Try again</button> </p> )} > <Suspense fallback={<p className="muted">Loading topic…</p>}> <TopicDetails id={selectedId} /> </Suspense> </ErrorBoundary> </div> </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 { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } 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.

Check yourself

  1. What does use do with a promise that hasn't resolved yet?
  2. Why must the promise passed to use be cached?
  3. When does a transition not stop a Suspense fallback from showing?

Was this article helpful?

Your response is saved on this device.