DEV Community

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>

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

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

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

Top comments (0)