Error_Boundaries_in_React_Updated
Error_Boundaries_in_React_Updated
Example Code:
import React from 'react';
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;
}
}
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 in React
Error Boundaries make React apps more robust by preventing whole app crashes and showing a friendly fallback UI
when parts of the UI fail.