Overview
Error handling in React helps prevent the app from crashing and improves user experience.
React doesn’t catch errors in event handlers or lifecycle methods with normal try-catch. Special mechanisms are required.
1. Error Boundaries
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree and display a fallback UI instead of crashing.
When to use them?
Wrap risky components: widgets, dashboards, charts, lazy-loaded components
Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true }; // update UI
}
componentDidCatch(error, errorInfo) {
console.error("Logged error:", error, errorInfo);
// log error to service
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Key Point:
- Error boundaries only catch errors during rendering, lifecycle methods, and constructors in the component tree.
2. Handling Errors in Event Handlers
- Error boundaries don’t catch errors in event handlers.
- Use
try...catch
inside the function.
function Button() {
const handleClick = () => {
try {
// risky logic
} catch (error) {
console.error("Caught in event:", error);
}
};
return <button onClick={handleClick}>Click</button>;
}
Key Point:
- Always use
try...catch
in event handlers and async functions.
3. Handling Async Errors
async function fetchData() {
try {
const response = await fetch('/api/data');
const json = await response.json();
} catch (err) {
console.error("Async error:", err);
}
}
Use try-catch for:
fetch()
/ API calls- File uploads
- Database operations
4. Summary
What to Know
- React error handling includes render-time errors, event handler errors, and async operation errors.
- Use Error Boundaries to catch render and lifecycle errors.
- Use
try...catch
for event handlers and async functions.
Error Types & Handling Methods
Error Type | How to Handle |
---|---|
Render/Lifecycle errors | Use Error Boundaries (getDerivedStateFromError , componentDidCatch ) |
Event handler errors | Use try...catch inside the event handler |
Async (API/fetch) errors | Use try...catch inside async functions |
Form/UI-level validation | Use local component state to show errors |
Best Practices
Practice | Why It Matters |
---|---|
Use Error Boundaries | Prevent the entire app from crashing on render errors |
Add try...catch in events | Catch and gracefully handle user-triggered logic errors |
Handle async errors properly | Avoid unhandled promise rejections in API calls |
Show fallback UI | Improve user experience with error messages or loaders |
Log errors to external services | Helps with debugging and monitoring in production |