Skip to content

Error Boundaries

The Course
•
15 min study

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.

A boundary per column React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import ErrorBoundary from "./ErrorBoundary.jsx"; import { columns, starterCards } from "./data.js"; // Pretend some saved data is broken: a card titled "crash" can't be shown. 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>; } export default function App() { const [cards, setCards] = useState(starterCards); const [title, setTitle] = useState(""); function addCard(event) { event.preventDefault(); if (title.trim() === "") return; setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: 15 }]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form className="toolbar" onSubmit={addCard}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> <button type="button" onClick={() => { throw new Error("Thrown in a click handler."); }}> Throw in a click </button> </form> <div className="board"> {columns.map((column) => ( <ErrorBoundary key={column.id} fallback={<p className="column error">{column.title} couldn't be shown.</p>}> <section className="column"> <h2>{column.title}</h2> <ul className="cards"> {cards.filter((card) => card.column === column.id).map((card) => ( <CardItem key={card.id} card={card} /> ))} </ul> </section> </ErrorBoundary> ))} </div> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; import { Component } from "react"; // Shows `fallback` instead of its children when rendering them throws. // Error boundaries are still written as classes: there's no hook for this. 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; } } 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; }
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.

Your working space React · 5 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import ErrorBoundary from "./ErrorBoundary.jsx"; import { columns, starterCards } from "./data.js"; // Pretend some saved data is broken: a card titled "crash" can't be shown. 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>; } export default function App() { const [cards, setCards] = useState(starterCards); const [title, setTitle] = useState(""); function addCard(event) { event.preventDefault(); if (title.trim() === "") return; setCards([...cards, { id: Date.now(), title: title.trim(), column: "todo", minutes: 15 }]); setTitle(""); } return ( <main> <h1>Study Board</h1> <form className="toolbar" onSubmit={addCard}> <input aria-label="New card" placeholder="New card" value={title} onChange={(e) => setTitle(e.target.value)} /> <button type="submit">Add</button> <button type="button" onClick={() => { throw new Error("Thrown in a click handler."); }}> Throw in a click </button> </form> <div className="board"> {columns.map((column) => ( <ErrorBoundary key={column.id} fallback={<p className="column error">{column.title} couldn't be shown.</p>}> <section className="column"> <h2>{column.title}</h2> <ul className="cards"> {cards.filter((card) => card.column === column.id).map((card) => ( <CardItem key={card.id} card={card} /> ))} </ul> </section> </ErrorBoundary> ))} </div> </main> ); } export const columns = [ { id: "todo", title: "To do" }, { id: "doing", title: "Doing" }, { id: "done", title: "Done" }, ]; export const starterCards = [ { id: 1, title: "Read about reducers", column: "todo", minutes: 20 }, { id: 2, title: "Draw the component tree", column: "doing", minutes: 15 }, { id: 3, title: "Practice useState", column: "done", minutes: 30 }, { id: 4, title: "Try context", column: "todo", minutes: 25 }, ]; import { Component } from "react"; // Shows `fallback` instead of its children when rendering them throws. // Error boundaries are still written as classes: there's no hook for this. 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; } } 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; }
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?

Show one solution

In ErrorBoundary.jsx:

JavaScript
reset = () => this.setState({ error: null });

render() {
  if (this.state.error) return this.props.fallback(this.reset);
  return this.props.children;
}

In App.jsx:

JSX
<ErrorBoundary
  key={column.id}
  fallback={(reset) => (
    <div className="column error">
      <p>{column.title} couldn't be shown.</p>
      <button onClick={() => {
        setCards(cards.filter((card) => !card.title.toLowerCase().includes("crash")));
        reset();
      }}>
        Remove broken cards
      </button>
    </div>
  )}
>

React batches the two updates, so the boundary re-renders its children with the broken card already gone.

Was this article helpful?

Your response is saved on this device.