Skip to content
ClapelloNotes by Barath
ReactCh 08 · 6/6
Core4 min readUpdated

React / 45

Error boundaries

TL;DR

A class component that catches render errors in its children and shows a fallback instead of a blank page. Still the one thing you can't do with a hook.

How it works

An error boundary is a class component with one or both of these methods:

MethodWhen React calls itIts job
static getDerivedStateFromError(error)During rendering, right after a child throwsReturn new state, e.g. { hasError: true }, so the next render shows the fallback. Must be pure.
componentDidCatch(error, info)In the commit phase, after the fallback is on screenSide effects: send error and info.componentStack to a logging service.

root

<App />

<Header />

still on screen

<Menu />

still on screen
<ErrorBoundary>

<Cart /> threw

replaced by

"Cart couldn't load. Try again"

Cart throws while rendering. The nearest error boundary above it swaps just that part for a fallback. Header and Menu keep working.

Write one (once)

ErrorBoundary.jsx
import { Component } from "react";
 
export class ErrorBoundary extends Component {
  state = { hasError: false };
 
  static getDerivedStateFromError() {
    return { hasError: true };
  }
 
  componentDidCatch(error, info) {
    console.error("Caught:", error, info.componentStack); // or your logger
  }
 
  render() {
    if (this.state.hasError) {
      return (
        <div role="alert">
          <p>{this.props.message ?? "Something went wrong."}</p>
          <button onClick={() => this.setState({ hasError: false })}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

Then wrap the risky parts:

App.jsx
<Header />
<Menu />
<ErrorBoundary message="Cart couldn't load.">
  <Cart />
</ErrorBoundary>

"Try again" clears the error, so the boundary renders its children again. If the bug is still there, it simply catches it again.

One broken widget, not a blank page

Try it

<Menu />

Paneer tikka

<ErrorBoundary>

<Cart />

2 items in your cart

  1. no errors yet
Break the cart. Only the part inside the boundary is replaced; the menu keeps working. Try again re-renders the children.

Where to put them

You don't wrap every component. Ask: "if this breaks, what should the user still be able to use?"

  • One near the top of the app, so nothing ever ends in a blank page.
  • One per independent area: a sidebar, a chart, the comments section, a lazy-loaded page. A broken chart shouldn't take the checkout with it.
  • Not around tiny pieces like each avatar or button. That's noise.

What it does not catch

Error boundaries catch errors thrown while React is rendering (and in lifecycle methods and effects) of the components below them. They do not catch:

  • Errors in event handlers (onClick): React isn't rendering at that moment. Use try/catch and put the error in state.
  • Async code like setTimeout or a fetch callback, for the same reason.
  • Errors thrown in the boundary itself: only a boundary higher up can catch those.
  • Errors during server-side rendering.

A common trick for the first two: catch the error and store it in state, then throw it during render so the boundary sees it.

Don't

Hoping a boundary catches a click error

<button onClick={() => {
  JSON.parse(badText); // throws in a handler
}}>
  Import
</button>
// boundary never sees it

Do

Handle it where it happens

function handleImport() {
  try {
    setData(JSON.parse(badText));
  } catch (err) {
    setError(err.message); // show it in the UI
  }
}

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.