React Error Boundary

On this page
  • Basic example
  • Custom fallback component

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

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

Custom fallback component

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 */}


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
Edit this page
Want to make your own site like this?
Try gatsby-theme-code-notes by Zander Martineau.
Notes on code. My second brain, by Zander Martineau.