Servers time out, databases go down. A failing page shouldn't take the whole site with it.
npm install and npm run dev. Follow Stats. The pretend service fails on its first request. Press Try again.
error.jsx
When app/stats/page.jsx throws, Next.js shows app/stats/error.jsx in its
place, inside the layout. The navigation still works, and so does every other
page. An error.jsx doesn't catch an error in the layout of its own segment;
that needs a boundary higher in the tree. global-error.jsx can handle a root
layout failure and must provide its own <html> and <body>.
"use client";
export default function StatsError({ error, retry }) { … }- An error file must be a client component: it has a button to press.
erroris what was thrown. The lab logserror.messageto the console.retry()asks the server for this part of the page again, and shows it if it works:
export default function StatsError({ error, retry }) {
useEffect(() => {
console.log("Stats failed:", error.message);
}, [error]);
return (
<main>
<h1>Stats</h1>
<p>Your stats couldn't be loaded.</p>
<button onClick={() => retry()}>Try again</button>
</main>
);
}Don't show error.message to readers
The page shows its own sentence, Your stats couldn't be loaded., not the error's message. On a real site built for production, Next.js hides the messages of errors thrown on the server, because they can contain details that aren't for the public, such as a database's address. The reader gets a generic message instead. Log the real one, to the console here or to an error-tracking service in a real app, and write the reader's message yourself.
retry and reset
Error files also receive reset. It only renders the page again with the
same failed result: it doesn't ask the server for anything. That helps when
the error came from something in the browser. When data from the server failed,
use retry.
Predict
Change the button to call reset() instead of retry(), taking reset from
the props. Press Run, follow Stats, and press Try again.
Check your prediction
The error stays: reset() shows the same failed result again, and the server is
never asked. Change it back to retry().
Knowing that retry is still working
retry() takes a moment: the server has to render the page again. Until it
answers, the button looks exactly as before, so a reader may think nothing
happened and press it again.
React's useTransition hook tracks this kind of slow work:
import { useTransition } from "react";
const [isPending, startTransition] = useTransition();startTransition(fn)callsfnand marks the updates it starts as a transition: work that may take a while, during which React keeps showing the current screen instead of a blank one.isPendingistruefrom the moment you callstartTransitionuntil everything it started has finished. Then it'sfalseagain.
retry() already runs inside a transition, but that one belongs to Next.js,
and your component can't see it. Call retry() inside your own
startTransition, and the refresh becomes part of your transition, so your
isPending covers it.
Trace one press of Try again with this in place:
- The click calls
startTransition(() => retry()).StatsErrorrenders again withisPendingtrue. The error page is still on screen. - The server renders the stats page again. The pretend service answers this time.
- The stats page replaces the error page, and the transition is over.
StatsErroris gone, so it never renders withfalseagain. Had the service failed a second time, the error page would stay, withisPendingback tofalse.
Predict
Add the hook to StatsError, with a log during render so you can watch it:
export default function StatsError({ error, retry }) {
const [isPending, startTransition] = useTransition();
console.log("isPending:", isPending);and change the button's click to () => startTransition(() => retry()).
Import useTransition next to useEffect. Press Run, follow Stats,
then press Try again. What does the console show after the click?
Check your prediction
isPending: true, once, and then the stats appear. Before the click,
StatsError logged isPending: false. There is no false afterwards,
because the error page is replaced by the stats page when the transition ends.
Keep these changes for the exercise, but remove the log.
Trying…
While the page is retrying, make the button say Trying… and disable it, so the reader knows something is happening and can't press it twice. Start from the code of the last Predict.
npm install and npm run dev. Hint 1: the idea
isPending is an ordinary value during render, like a prop. Anything the
button shows can depend on it, including whether it can be pressed.
Hint 2: a first step
Make sure the click goes through startTransition, or isPending never
becomes true. Then change the button in two places: an attribute that stops
it being pressed, and its text.
Show one solution
import { useEffect, useTransition } from "react";const [isPending, startTransition] = useTransition();<button onClick={() => startTransition(() => retry())} disabled={isPending}>
{isPending ? "Trying…" : "Try again"}
</button>disabled stops a second press while the first retry is still running, and the
label tells the reader why. Nothing needs resetting afterwards: if the retry
works, the stats page replaces the error page; if it fails, isPending is
false again and the button comes back. Calling retry() without
startTransition would leave isPending false the whole time.
Completion is saved in this browser only. It does not measure mastery.