Skip to content
React

Error Boundaries

Catch component errors.

By EZ4Code Team
reacterror

Code

import { Component } from 'react';

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

    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        console.error('Error caught:', error, errorInfo);
        // Report errors to monitoring service
        // logErrorToService(error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            // Custom fallback UI
            if (this.props.fallback) {
                return this.props.fallback(this.state.error);
            }

            return (
                <div style={{ padding: 20, color: 'red' }}>
                    <h2>Something went wrong</h2>
                    <p>{this.state.error?.message}</p>
                    <button onClick={() => this.setState({ hasError: false })}>
                        Try Again
                    </button>
                </div>
            );
        }

        return this.props.children;
    }
}

// Usage
function App() {
    return (
        <ErrorBoundary
            fallback={(error) => (
                <div>Custom error: {error.message}</div>
            )}
        >
            <Header />
            <ErrorBoundary>
                <Widget />
            </ErrorBoundary>
            <Footer />
        </ErrorBoundary>
    );
}

// Functional error boundary (React 19+)
// function ErrorBoundary({ children, fallback }) {
//     return <ErrorBoundaryClass fallback={fallback}>{children}</ErrorBoundaryClass>;
// }

Explanation

Error boundaries catch child component render errors; getDerivedStateFromError updates state; componentDidCatch logs errors.

More React Snippets