← React Beginner Questions - Set 4 Q31

What is the purpose of error boundaries in React?

React Beginner Questions - Set 4

A component that catches render-time errors in its subtree and shows a fallback instead of a blank page. They are still class-only.

Example

import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.error('Boundary caught:', error, info.componentStack);
  }

  render() {
    if (this.state.error) {
      return <div role="alert">Something broke: {this.state.error.message}</div>;
    }
    return this.props.children;
  }
}

// <ErrorBoundary><Chart /></ErrorBoundary>

What to notice

← Back to the question list