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
Controlled Form with Validation
Build a controlled React form with inline validation and error messages.
Event Handling and List Rendering
Handle events and render dynamic lists with keys in React.
useState
State management Hook.
useEffect
Side-effect Hook.
useContext
Shared state via context.
useReducer
Complex state management.