When a component throws while rendering, React can't show a half-finished
screen, so by default it removes the whole app. You saw that in the
beginner course's bug hunt: one mistake, a blank page. An error boundary
catches rendering errors below it and shows a fallback instead, so one broken
part doesn't take everything down.
Runs with Vite on your computer: unzip, then npm install and npm run dev.
This board pretends some saved data is broken: a card titled crash throws
while rendering. Add a card called crash test:
JSX
function CardItem({ card }) { if (card.title.toLowerCase().includes("crash")) { throw new Error(`Card ${card.id} has broken data.`); } return <li className="card">{card.title}</li>;}
What you'll see
To do couldn't be shown. replaces that column. Doing and Done keep
working. The console shows React's report of the error, and the boundary's own
log line, Caught by a boundary.
A class component
JavaScript
export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidCatch(error, info) { console.log("Caught by a boundary:", error.message); } render() { if (this.state.error) return this.props.fallback; return this.props.children; }}
Error boundaries are the one thing you still write as a class: there's no hook
for catching rendering errors. You haven't needed classes before, so here is
what each new piece of syntax means:
class ErrorBoundary extends Component defines a component as a class
instead of a function. extends Component gives it React's built-in
component behaviour, such as setState.
Inside the class, name = value (here state = { error: null }) is a
class field: every boundary gets its own copy, like each useState call
gives each component its own state. The state field is the class version of
the initial value you'd pass to useState.
this means "this particular boundary". this.state is its state and
this.props its props. A class component reads props from this.props
rather than from a function parameter.
this.setState({ error: null }) is the class version of a state setter. It
merges the object you give it into this.state and re-renders.
render() is a method React calls to get the JSX. It does the job of the
function body in a function component.
static marks a method React calls on the class itself, not on one
boundary. You only need it for getDerivedStateFromError.
You won't write classes anywhere else in this course. To add a method of your
own, write it as a class field holding an arrow function,
handleSomething = () => { ... };, so this still means the boundary when
someone else calls it.
getDerivedStateFromError turns the error into state, so the next render
shows the fallback.
componentDidCatch is for side effects, such as sending the error to a
logging service.
Many projects install a small package, react-error-boundary, instead of
writing this class. It does the same thing, with a few conveniences.
What a boundary can't catch
Press Throw in a click. The console shows the error, but no fallback
appears, and the board keeps working. Boundaries catch errors during
rendering, in lifecycle code and in effects. They don't catch errors in:
event handlers, which run after rendering; use try/catch there;
async code such as a setTimeout or an awaited request, unless you put
the error into state, which then throws during render;
the boundary itself;
server rendering in the same way as this client-only class example.
React Actions are a special case: errors thrown inside a startTransition
action can reach an error boundary. For expected validation or request failures,
keep returning a useful form error as on Day 6. Don't treat every async callback
as an Action.
Where to put boundaries
One around the whole app is the minimum: a friendly "Something went wrong"
beats a blank page. Finer ones, around independent areas such as each column, a
sidebar or a widget, let the rest keep working. The Study Board puts one around
each column.
Recovering
Add another card now: To do stays broken. Once a boundary has caught an
error, it keeps showing the fallback until something resets it. Removing the
broken data alone isn't enough.
Exercise
Remove broken cards and try again
Give the To do fallback a button, Remove broken cards, that removes
every card titled crash and shows the column again.
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea
Only the boundary can clear its own error, but the button lives in the
fallback that App passes in. So the boundary has to hand the fallback a way
to reset it. If fallback were a function instead of JSX, the boundary could
call it with that reset function as an argument.
Hint 2: a first step
In ErrorBoundary.jsx, add a reset class field: an arrow function that sets
the error back to null (see the syntax list above). Then change render to
call this.props.fallback with it. Now add a crash card: the whole board
disappears. Read the console's error: what is App still passing as
fallback, and what does the boundary now expect it to be?