Skip to main content

Catching rendering errors with an error boundary

By default, if your application throws an error during rendering, React will remove its UI from the screen. To prevent this, you can wrap a part of your UI into an error boundary. An error boundary is a special component that lets you display some fallback UI instead of the part that crashed—for example, an error message.

A nice library which provides a simple way to create an error boundary is react-error-boundary

npm install react-error-boundary
# or
yarn add react-error-boundary
info

Note ErrorBoundary is a client component. When using NextJS you can only pass props to it that are serializeable or use it in files that have a 'use client' directive.

The simplest way to use ErrorBoundary is to wrap it around the main (App?) component of your application. This way, if any of the child components throw an error, the fallback UI will be displayed:

import { ErrorBoundary } from "react-error-boundary";

const App = () => {
return (
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<AppComponents etc={}/>
</ErrorBoundary>
)
}
export default App

The fallback prop can be any React element you want to display when an error occurs.

With details

You can also provide a custom error message and a stack trace to the fallback UI:

import {useState, useEffect} from "react";
import Fishy from "./Fishy";
import { ErrorBoundary } from "react-error-boundary";


function fallbackRender({ error, resetErrorBoundary }) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.

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


const App = () => {


return (
<ErrorBoundary fallbackRender={fallbackRender}>
<div >
<Fishy />
</div>
</ErrorBoundary>
);
}

export default App;

The Fishy component is a component that throws an error. If an error occurs, the fallbackRender function will be called with the error object .

import { useEffect } from 'react'

const Fishy = () => {

useEffect(() => {
throw new Error('BOOM')
}, [])

return (
<div>
<h1>🐟</h1>
</div>
)
}

export default Fishy