React
April 7, 20252 min read...
ReactApril 7, 20252 min read

React Error Boundaries: Catching and Handling Errors Gracefully

Learn how to use React Error Boundaries to catch JavaScript errors in components, display fallback UI, log errors, and recover gracefully. Includes patterns for async errors and error recovery.

React Error Boundaries: Catching and Handling Errors Gracefully

What Are Error Boundaries?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI instead of crashing the whole app.

Creating an Error Boundary (Class Component)

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

static getDerivedStateFromError(error) { return { hasError: true, error }; }

componentDidCatch(error, errorInfo) { console.error(‘Logged:’, error, errorInfo); // Send to Sentry/LogRocket }

render() { if (this.state.hasError) { return this.props.fallback || <div>Something went wrong</div>; } return this.props.children; } }

Using with Hooks (react-error-boundary library)

import { ErrorBoundary } from ‘react-error-boundary’;

function fallbackRender({ error, resetErrorBoundary }) { return ( <div role=“alert”> <p>Something failed: {error.message}</p> <button onClick={resetErrorBoundary}>Try again</button> </div> ); }

function App() { return ( <ErrorBoundary fallbackRender={fallbackRender} onReset={() => window.location.reload()}> <MyComponent /> </ErrorBoundary> ); }

Async Error Handling

Error boundaries don’t catch errors in event handlers or async code. Use try/catch:

function handleSubmit() {
try {
await saveData();
} catch (error) {
setError(error); // display error in component state
}
}

Production Tips

  • Place boundaries at feature boundaries (e.g., each widget or route)
  • Provide specific fallbacks per feature
  • Log errors to monitoring service

Interview Q&A

Q: Why are error boundaries class components? Hooks have no equivalent for getDerivedStateFromError or componentDidCatch. The react-error-boundary library provides a hook-friendly wrapper.

Conclusion

Error boundaries are essential for production React apps. Wrap each major UI section to prevent cascading failures.

Comments

Join the conversation — sign in to leave a comment.