Search⌘ K
AI Features

Implementing an Error Boundary

Explore how to implement error boundaries in React class components to catch and manage errors in the component tree. Understand the use of getDerivedStateFromError and componentDidCatch lifecycle methods for state updates and error logging. Learn to display fallback UI while isolating errors, improving app stability and user experience.

There are two simple rules when it comes to implementing an error boundary:

  1. Only Class components can be turned into an error boundary.
  2. The class has to implement the static getDerivedStateFromError() method or the class method componentDidCatch() (or both of them).

Strictly speaking, we are already dealing with an error boundary from a technical point of view if one or both of the methods mentioned above have been implemented. All other rules that apply to regular class components also apply to error boundary.

Let’s look at an implementation of an error boundary:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';
require('./style.css');

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

The console would look like this once you press the button:


Defining a new component

First, we define a new component. We have named this component ErrorBoundary, but it is possible to give it any other ...