Error Boundaries

Catch Rendering Errors

Example

An error in rendering normally unmounts the whole app. An error boundary (must be a class) shows a fallback for its part of the tree only.

import { Component, useState } from 'react';

class ErrorBoundary extends Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(error) {
    console.log('Logged to monitoring:', error.message);
  }
  render() {
    return this.state.hasError ? <p style={{ color: 'crimson' }}>Something went wrong in this widget.</p> : this.props.children;
  }
}

function Buggy({ crash }) {
  if (crash) throw new Error('Widget crashed');
  return <p>Widget works fine.</p>;
}

export default function App() {
  const [crash, setCrash] = useState(false);
  return (
    <div>
      <button onClick={() => setCrash(true)}>Crash the widget</button>
      <ErrorBoundary><Buggy crash={crash} /></ErrorBoundary>
      <p>The rest of the page keeps working.</p>
    </div>
  );
}

Result

Note: Error boundaries do not catch errors in event handlers or async code; use try/catch there.