React5 min read
React Error Boundaries
Catch JavaScript errors in components and show fallback UI.
Sarah Johnson
December 20, 2025
0.0k0
Error Boundaries catch errors in component tree and show fallback UI.
Creating Error Boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.log('Error:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Using It
function App() {
return (
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>
);
}
Multiple Boundaries
<ErrorBoundary>
<Header />
<ErrorBoundary>
<Content />
</ErrorBoundary>
<Footer />
</ErrorBoundary>
Remember
- Must be class component
- Catches render errors
- Shows fallback UI
- Doesn't catch event handler errors
Next: Learn API integration!
#React#Error Handling#Error Boundaries#Intermediate