Course contentsShow
← React
Lesson 1301 of 2,39633. Error BoundariesFree lesson

Minimal Error Boundary Implementation

Building the simplest possible error boundary class that catches errors and displays a fallback message.

Minimal Error Boundary Implementation

You'll learn how to build the simplest functional error boundary to catch rendering errors in your React app.

The Absolute Minimum

An error boundary needs only two things to work: getDerivedStateFromError to update state when an error occurs, and a render method that shows either your children or a fallback UI. That's it—you can catch errors with just these pieces.

Think of it like a safety net at a circus: you don't need a fancy mechanism, just something that catches the performer if they fall and a way to signal "performance paused" to the audience.

Building the Simplest Boundary

Here's a minimal implementation that actually works:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so next render shows fallback
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

// Use it:
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>

What Makes This "Minimal"

This boundary has exactly what React requires: a boolean flag to track error state, the static method to flip that flag when errors happen, and conditional rendering to show either the fallback or children. No error logging, no reset buttons, no fancy recovery—just error catching in its purest form.

When any child component throws during rendering, getDerivedStateFromError catches it, sets hasError: true, and the next render displays your fallback message instead of crashing the entire app.

Key Takeaway: A working error boundary only needs getDerivedStateFromError to update state and conditional rendering to display a fallback—everything else is optional enhancement.