⚛ React Error Boundary

👋 FYI, this note is over 6 months old. Some of the content may be out of date.
On this page

From the React docs on Error boundaries:

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

Use this component to wrap other components that might crash so errors can be caught.

Basic example Jump to heading

<Suspense fallback={<Loader />}>
{/* A component that fetches data */}

Custom fallback component Jump to heading

A custom fallback component can be passed to the ErrorBoundary component, like so:

<ErrorBoundary fallback={<div>Error loading the cohort list</div>}>
<Suspense fallback={<Loader />}>
{/* A component that fetches data */}

Source Jump to heading

import React, { ReactNode } from 'react'
import { Alert } from 'theme-ui'

export interface ErrorBoundaryProps {
fallback?: ReactNode

interface ErrorBoundaryState {
hasError: boolean
error: Error | null

export class ErrorBoundary extends React.Component<
> {
state = { hasError: false, error: null }

static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return {
hasError: true,

render(): ReactNode {
if (this.state.hasError) {
const fallback = this.props.fallback
if (typeof fallback === 'string') {
return <Alert variant="warning">{fallback}</Alert>
} else if (fallback) {
return fallback

return (
<Alert variant="warning">
Something went wrong. Please refresh the page and try again.
return this.props.children

← Back home