How to use Error Boundaries in React
Error Boundaries provide a way to catch JavaScript errors anywhere in the React component tree and display fallback UI instead of crashing the entire application.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented error boundaries in countless React applications to provide graceful error handling and better user experience.
From my 25 years of experience in web development and 11 years with React, the most effective approach is to create class components that implement componentDidCatch and getDerivedStateFromError lifecycle methods.
This pattern prevents application crashes and provides meaningful error feedback to users.
Create a class component that implements componentDidCatch and getDerivedStateFromError to catch errors in child components.
import React from 'react'
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by boundary:', error, errorInfo)
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong.</h2>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
)
}
return this.props.children
}
}
// Usage
function App() {
return (
<ErrorBoundary>
<Header />
<MainContent />
<Footer />
</ErrorBoundary>
)
}
The getDerivedStateFromError static method updates state to trigger fallback UI rendering when an error occurs. The componentDidCatch method logs error details for debugging and monitoring. Error boundaries only catch errors in child components during rendering, lifecycle methods, and constructors - they don’t catch errors in event handlers, async code, or the error boundary itself. Wrap components strategically to isolate error-prone sections while maintaining application functionality.
This is the same error boundary pattern we use in CoreUI React admin templates to ensure robust application stability and user experience. For production applications, integrate error boundaries with error reporting services like Sentry to automatically track and monitor JavaScript errors in your React components.



