Skip to main content

Error Boundary

In React, an ErrorBoundary is a component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the entire app. Error boundaries are typically used to handle errors that occur during rendering, in lifecycle methods, or in constructors of the whole component tree.

Creating an Error Boundary

To create an error boundary, you need to create a class component that implements the componentDidCatch lifecycle method and optionally a static getDerivedStateFromError method.

import React, { Component } from 'react';

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

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

componentDidCatch(error, errorInfo) {
console.error('Error caught by Error Boundary:', error);
console.error('Error info:', errorInfo);
}

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

return this.props.children;
}
}

export default ErrorBoundary;

Using the Error Boundary

Wrap the ErrorBoundary component around other components where you want to catch errors:

import React from 'react';
import ErrorBoundary from './ErrorBoundary'; // Assuming ErrorBoundary is in the same directory

const ProblematicComponent = () => {
throw new Error('Oops! Something went wrong.');
return <div>Will not render</div>;
};

const App = () => (
<ErrorBoundary>
<ProblematicComponent />
</ErrorBoundary>
);

export default App;