23. Error Boundaries and Handling Errors
Level: AdvancedDuration: 22m
Why Errors Happen in React
React apps can break due to undefined variables, bad API responses, or unexpected bugs. Without error handling, a small bug in one component can crash your entire app.
What Is an Error Boundary?
An Error Boundary is a special React component that catches runtime errors in its child components during rendering and replaces the broken UI with a fallback instead of crashing the whole app.
- Prevents full app crashes
- Displays fallback UIs
- Logs errors for debugging
- Improves user experience
Creating a Basic Error Boundary
jsx
import React, { Component } from 'react'
class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, info) {
console.error('Error caught by Error Boundary:', error, info)
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>
}
return this.props.children
}
}
export default ErrorBoundaryUsing an Error Boundary
jsx
import ErrorBoundary from './ErrorBoundary'
import Profile from './Profile'
export default function App() {
return (
<ErrorBoundary>
<Profile />
</ErrorBoundary>
)
}Custom Fallback UI
jsx
class ErrorBoundary extends Component {
...
render() {
if (this.state.hasError) {
return (
<div>
<h2>Oops! Something broke.</h2>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
)
}
return this.props.children
}
}Handling Errors in Event Handlers
Error Boundaries do not catch errors inside event handlers. Use try/catch manually:
jsx
function handleClick() {
try {
throw new Error('Button failed!')
} catch (error) {
console.error(error)
}
}
<button onClick={handleClick}>Click me</button>Handling Async Errors
Async errors are not caught by Error Boundaries, so you must handle them in promises or async/await.
jsx
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch('/api/data')
if (!res.ok) throw new Error('API failed')
} catch (error) {
console.error(error)
}
}
fetchData()
}, [])Best Practices
- Use multiple small Error Boundaries per feature
- Show user-friendly fallback messages
- Log errors to a monitoring service (e.g. Sentry)
- Don’t hide all errors—fail safely, not silently
Mini Project Step
Wrap your main feature components with Error Boundaries. Add a custom fallback UI that lets users retry or go back to safety without crashing the entire app.