Skip to main content

Catching Errors in react with example

ยท 3 min read
Parth Maheta

An error boundary in React is a way to handle JavaScript errors that occur during the rendering of a component tree. It helps prevent the entire application from crashing due to a single component's error. Instead, error boundaries catch errors and allow you to gracefully handle them by displaying a fallback UI or logging the error for further investigation.

Here's a simple explanation of error boundaries in React for beginners:

  1. Error Propagation in React:

    • In a typical React application, if an error occurs in a component's render method or during the lifecycle methods, it can lead to the entire application crashing.
    • React's default behavior is to unmount the entire component tree when an error occurs.
  2. Error Boundary Concept:

    • An error boundary is a component in React that acts as a boundary for catching JavaScript errors that occur during rendering.
    • When an error occurs within the subtree of an error boundary component, it will capture the error and prevent it from affecting the entire component tree.
  3. How to Define an Error Boundary:

    • To define an error boundary, you create a class component that implements either or both of the lifecycle methods static getDerivedStateFromError and componentDidCatch.
    • These methods allow you to catch errors during the rendering phase and provide an opportunity to handle them.
  4. Example Error Boundary Component:

    import React, { Component } from 'react';

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

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

    componentDidCatch(error, errorInfo) {
    // You can log the error for further investigation
    console.error('Error caught by error boundary:', error, errorInfo);
    }

    render() {
    if (this.state.hasError) {
    // Render a fallback UI when an error occurs
    return <p>Something went wrong. Please try again later.</p>;
    }

    // Render the children if no error occurred
    return this.props.children;
    }
    }

    export default ErrorBoundary;
  5. Using Error Boundary:

    • Wrap the component tree or specific components with the error boundary component.
    • When an error occurs within the error boundary's subtree, it will trigger the error boundary's methods, and you can provide a fallback UI or handle the error as needed.
  6. Usage Example:

    import React from 'react';
    import ErrorBoundary from './ErrorBoundary';
    import MyComponent from './MyComponent';

    const App = () => {
    return (
    <ErrorBoundary>
    <MyComponent />
    </ErrorBoundary>
    );
    };

    export default App;

By using error boundaries in your React application, you can improve its robustness and provide a better user experience by handling errors gracefully rather than crashing the entire application.