What does this Suspense example log and show after you show, hide, and show the notes again?
Notes reads its text with use from a small cache. The first request answers after 20 ms. Spinner, the fallback, logs from an Effect, so it only logs once it's on the screen.
import { Suspense, use, useEffect, useState } from "react";
const cache = new Map();
function getNotes(id) {
if (!cache.has(id)) {
console.log("fetch", id);
cache.set(id, new Promise((resolve) => setTimeout(() => resolve("Grassy and bright."), 20)));
}
return cache.get(id);
}
function Notes({ id }) {
const notes = use(getNotes(id));
console.log("Notes renders with", notes);
return <p>{notes}</p>;
}
function Spinner() {
useEffect(() => {
console.log("fallback on screen");
});
return <p>Loading notes…</p>;
}
export default function App() {
const [shown, setShown] = useState(false);
return (
<>
<h1>Sencha</h1>
<button onClick={() => setShown(!shown)}>{shown ? "Hide notes" : "Show notes"}</button>
{shown && (
<Suspense fallback={<Spinner />}>
<Notes id="sencha" />
</Suspense>
)}
</>
);
}
It runs in development, rendered as <App />, and then:
- You click Show notes.
- You wait until the notes have loaded.
- You click Hide notes, then Show notes again.
Practice it in the editor, with tests
The answer
Work out every line it logs, in order, and what the page shows at the end. Then check.
Checking your sign-in…