React Error Boundaries

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

Why Use Error Boundaries?

React components can crash due to bugs or unexpected data. Without error boundaries, a single component error could take down your entire app. Using error boundaries improves user experience by showing a friendly message instead of a blank screen.

Example

import React from 'react';


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


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


  componentDidCatch(error, info) {
    console.error('Error caught:', error, info);
  }


  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }


    return this.props.children;
  }
}


// Usage
<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>


export default ErrorBoundary;

Conclusion

Error boundaries help prevent full app crashes and improve resilience. They are a must-have for production React apps.

Leave a comment

Your email address will not be published. Required fields are marked *