You switch tabs in a transition, and the new tab suspends. What's on screen right after the click, and what does it log?
The Reviews tab reads a promise with use; it resolves 20 ms after it's first asked for. App logs every time it renders, and its Effect logs every time a render reaches the screen.
import { Suspense, use, useEffect, useState, useTransition } from "react";
let reviewsPromise;
function getReviews() {
reviewsPromise ??= new Promise((resolve) => setTimeout(() => resolve("Five stars."), 20));
return reviewsPromise;
}
function Reviews() {
const reviews = use(getReviews());
return <p>{reviews}</p>;
}
export default function App() {
const [tab, setTab] = useState("about");
const [isPending, startTransition] = useTransition();
console.log("render", tab, isPending);
useEffect(() => {
console.log("on screen", tab, isPending);
});
return (
<>
<button onClick={() => startTransition(() => setTab("reviews"))}>Reviews</button>
{isPending && <span>(loading)</span>}
<Suspense fallback={<p>Loading reviews…</p>}>
{tab === "about" ? <p>A small tea shop.</p> : <Reviews />}
</Suspense>
</>
);
}
It runs in development, rendered as <App />, and then:
- You click Reviews, and wait for the reviews.
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…