Create a Custom React Error Boundary
Use this AI prompt to create a robust React Error Boundary component that catches runtime errors, displays fallback UI, and integrates gracefully into your app.
🧠 What This Prompt Does
This prompt generates a reusable React Error Boundary that gracefully handles runtime crashes and displays a fallback UI instead of breaking the entire app.
It helps you ensure robust user experiences and easier debugging during production.
💬 The Prompt
You are a senior React engineer.
Generate a reusable Error Boundary component in TypeScript that:
- Catches rendering errors in child components
- Displays a fallback UI
- Logs errors to the console or an external service
- Provides a reset option for users
Also explain where and how to wrap components with this Error Boundary.
⚙️ Example Output (AI Generated)
import React, { Component, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
}
class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('ErrorBoundary caught an error:', error, info);
}
handleReset = () => this.setState({ hasError: false });
render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div className='flex flex-col items-center justify-center p-8 text-center'>
<h2 className='text-lg font-semibold text-red-500'>
Something went wrong.
</h2>
<button
onClick={this.handleReset}
className='mt-4 px-4 py-2 bg-blue-500 text-white rounded-md'>
Try again
</button>
</div>
)
);
}
return this.props.children;
}
}
export default ErrorBoundary;
📘 When to Use This Prompt
- When your React app can break due to third-party or async issues.
- For large applications where feature isolation is important.
- To enhance user experience by replacing blank screens with helpful fallback UI.
💡 Best Practices
- Place one Error Boundary at the App root, and optionally per route or feature.
- Log captured errors to your monitoring system.
- Use different fallback UIs for critical and non-critical sections.
- Combine with Suspense boundaries for async operations.
🏁 Summary
This prompt creates a reliable, customizable Error Boundary that improves app stability and debugging efficiency.
Integrate it across your routes or feature modules to deliver a safer and more professional UX in your React apps.
reacterror-boundaryerror-handlingtypescriptai-prompt
Advertisement