DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Wahid Ibrahimy
Wahid Ibrahimy

Posted on

Use react-error-boundary to handle errors in React

React 16 introduced a new concept of an β€œerror boundary”.
An "Error Boundary" is a special component that you write to handle runtime errors. For a component to be an Error Boundary:

1- It must be a class component πŸ™
2- It must implement either getDerivedStateFromError or componentDidCatch.

Luckily, we have react-error-boundary which exposes the last Error Boundary component anyone needs to write because it gives you all the tools you need to declaratively handle runtime errors in your React apps.

So let's add react-error-boundary package and render the ErrorBoundary component:

import React from 'react';
import {ErrorBoundary} from 'react-error-boundary'
import "./style.css";

function ErrorFallback({error}) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <pre style={{color: 'red'}}>{error.message}</pre>
    </div>
  )
}

function Greeting({subject}) {
  return <div>Hello {subject.toUpperCase()}</div>
}

function Farewell({subject}) {
  return <div>Goodbye {subject.toUpperCase()}</div>
}

export default function App() {
  return (
    <div>
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <Greeting />
        <Farewell />
      </ErrorBoundary>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.