MediumAdvanced Patterns📖 Theory Question

What is Error Boundary and how do you implement one?

💡

Hint

Class component wrapping the tree — catches render errors and shows fallback UI instead of blank screen

Full Answer

Error Boundaries catch JavaScript errors during rendering, in lifecycle methods, and in constructors of child components. They must be class components (no hook equivalent yet).

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

  // Render phase — update state to show fallback
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  // Commit phase — log error to monitoring service
  componentDidCatch(error, info) {
    logErrorToSentry(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? 

Something went wrong.

; } return this.props.children; } } // Usage — wrap features, not the entire app function App() { return ( }> }> ); } // react-error-boundary library — hook-friendly wrapper import { ErrorBoundary } from 'react-error-boundary';
💡 Error boundaries do NOT catch errors in event handlers, async code (setTimeout, fetch), or SSR. Use try/catch for those. Place boundaries at feature level, not component level — granular boundaries give better UX.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint