Error Boundaries — React

An uncaught error while rendering removes the app's whole UI. An error boundary is a class component (a component written with class) that catches that error…

When a component throws an error while rendering and nothing catches it, React removes the app's whole UI, and the screen goes blank. An error boundary is a component that catches errors from the components inside it while they render. The error boundary then shows a backup UI (a fallback UI, often just called the fallback) in place of those components, and the rest of the app keeps working. It's like the circuit breakers (safety switches for the electricity) in a house, one per room. If there's a short circuit in the kitchen, only the kitchen breaker switches off, and only the kitchen lights go out. The living room stays lit. Without a breaker per room, one short circuit cuts the power to the whole house. In React, the breaker is the error boundary, and a room is the part of the app it wraps. The short circuit is an error while rendering, and the dark house is the blank screen.

One error, one blank screen

In this example, Profile shows the name of user, and App has a button that replaces user with null:

function Profile({ user }) {
  return <p>Hello, {user.name}</p>
}

function App() {
  const [user, setUser] = useState({ name: "Budi" })
  return (
    <div>
      <Profile user={user} />
      <p>Balance: $250</p>
      <button onClick={() => setUser(null)}>Break the data</button>
    </div>
  )
}

Click "Break the data": Profile renders again with user set to null, and user.name throws an error. In Chrome the message is TypeError: Cannot read properties of null (reading 'name'). Nothing catches that error, so React removes all of App's UI, including the balance, which did nothing wrong.

Building an ErrorBoundary

An error boundary has to be written as a class component: a component made with class, not with a function. React still has no built-in hook for error boundaries.

class ErrorBoundary extends React.Component {
  state = { hasError: false }

  static getDerivedStateFromError(error) {
    return { hasError: true }
  }

  componentDidCatch(error, info) {
    console.log("Caught:", error.message)
  }

  render() {
    if (this.state.hasError) {
      return <div id="fallback">An error occurred</div>
    }
    return this.props.children
  }
}

function App() {
  // ... user, setUser as before
  return (
    <div>
      <ErrorBoundary>
        <Profile user={user} />
      </ErrorBoundary>
      <p>Balance: $250</p>
    </div>
  )
}
Event hasError What shows
Page opens false Hello, Budi and Balance: $250
Click "Break the data" true An error occurred and Balance: $250

The balance is outside the boundary, so it still shows. Just like a breaker: only the room with the short circuit goes dark.

Try again: back to the normal UI

A fallback usually has a "Try again" button that runs this.setState({ hasError: false }) (how a class component changes its state), so the boundary shows its children again. Fix the cause first: if user is still null, Profile throws again right away and the fallback appears again.

The UI pattern is the same as ordinary conditional rendering: one boolean state picks one of two views. In the second exercise, you write that pattern with useState:

function App() {
  const [hasError, setHasError] = useState(false)
  return (
    <div>
      {hasError ? (
        <div id="error-ui">Oops! Something went wrong.</div>
      ) : (
        <div id="normal-ui">Everything is running normally</div>
      )}
      <button id="trigger" onClick={() => setHasError(true)}>Trigger Error</button>
      <button id="reset" onClick={() => setHasError(false)}>Reset</button>
    </div>
  )
}

What it doesn't catch

Take a guess first. Inside an ErrorBoundary there's a button with onClick={() => { throw new Error("Failed to save") }}, and the button is clicked. Does the fallback appear?

No, it doesn't. An error boundary only catches errors that happen while React is rendering: inside a component function, in a constructor, and in lifecycle methods such as componentDidMount. Lifecycle methods are class methods that React calls at a certain stage, for example componentDidMount after mount. These are not caught:

For event handlers and async code, catch the error yourself with try/catch, then keep the message in state so it can be shown. In this example, saveData() is the code that can fail, and setMessage is the setter of the message state:

function handleSave() {
  try {
    saveData()
  } catch (error) {
    setMessage("Failed to save: " + error.message)
  }
}

⚠️ Expecting a boundary to catch everything

TL;DR: An uncaught error while rendering removes the app's whole UI. An error boundary is a class component (a component written with class) that catches that error. It has static getDerivedStateFromError (which sets the state to { hasError: true }) and componentDidCatch(error, info) (which records the error). While hasError is true, render() shows a fallback (a backup UI) such as <div id="fallback">An error occurred</div>, and the parts outside the boundary keep showing. To go back to the normal UI, call setState({ hasError: false }) once the cause is fixed. A boundary doesn't catch errors in event handlers, in async code, or in itself. Catch errors in event handlers and async code with try/catch, and keep the message in state.

⚡ One error, one blank screen

Guess first: the component Profile shows user.name, and next to it App shows a balance. Then user becomes null, so user.name throws while rendering. What's left on screen?

Nothing. An uncaught error while rendering makes React remove the whole App UI, including the balance that did nothing wrong.

Meaning: An error boundary is a component that catches errors from the components inside it while they render, then shows a backup UI (a fallback) in place of those components only. The damage stays inside the part it wraps.

⚡ Making an ErrorBoundary

Write:

class ErrorBoundary extends React.Component {
  state = { hasError: false }

  static getDerivedStateFromError(error) {
    return { hasError: true }
  }

  render() {
    if (this.state.hasError) {
      return <div id="fallback">An error occurred</div>
    }
    return this.props.children
  }
}

Meaning: An error boundary is written as a class component (a component made with class). React calls getDerivedStateFromError when a component inside the boundary throws while rendering. This method sets hasError to true, then render() shows the fallback. When there's no error, render() shows this.props.children, which is what the boundary wraps. Everything outside the boundary stays on screen.

⚡ What it doesn't catch

Write:

function handleSave() {
  try {
    saveData()
  } catch (error) {
    setMessage("Failed to save: " + error.message)
  }
}
Guess first: a button inside an ErrorBoundary throws an error in its onClick. Does the fallback appear?

No. A boundary only catches errors while React is rendering. While a handler runs, React isn't rendering, so the error never reaches the boundary.

Meaning: For errors in event handlers and async code (for example setTimeout or fetch), catch the error yourself with try/catch. In the code above, saveData() is the code that can fail, and setMessage keeps the error message in state so it can be shown.

What you will learn