Error Boundaries in React
What are Error Boundaries?
Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those
errors, and display a fallback UI instead of crashing the whole app.
They catch errors during:
- Rendering
- Lifecycle methods
- Constructors of child components
How to Create an Error Boundary
You create an Error Boundary by writing a class component with:
- static getDerivedStateFromError(error)
- componentDidCatch(error, info)
Example Code:
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 ErrorBoundary:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
How to Use ErrorBoundary:
import ErrorBoundary from './ErrorBoundary';
import BuggyComponent from './BuggyComponent';
function App() {
return (
<div>
<ErrorBoundary>
<BuggyComponent />
Error Boundaries in React
</ErrorBoundary>
</div>
);
}
Example BuggyComponent:
function BuggyComponent() {
throw new Error('I crashed!');
return <div>Buggy Component</div>;
}
Important Points:
- Only class components can be Error Boundaries (React 18).
- Error boundaries do not catch errors in:
- Event handlers (use try/catch inside the handler)
- Asynchronous code like setTimeout
- Server-side rendering
- Use multiple boundaries to isolate different parts of the UI.
Conclusion:
Error Boundaries make React apps more robust by preventing whole app crashes and showing a friendly fallback UI
when parts of the UI fail.