Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React - Error Boundaries

Handling errors with error boundaries

Error boundaries are a powerful feature in React that allows you to catch JavaScript errors anywhere in your component tree, log those errors, and display a fallback UI instead of crashing the whole application. This tutorial covers how to create and use error boundaries to handle errors gracefully.

Key Points:

  • Error boundaries catch JavaScript errors anywhere in their child component tree.
  • Error boundaries can log errors and display a fallback UI.
  • Error boundaries do not catch errors for event handlers, asynchronous code, or server-side rendering.

Creating an Error Boundary

To create an error boundary, you define a class component that implements either static getDerivedStateFromError() or componentDidCatch() (or both).


// src/components/ErrorBoundary.js
import React, { Component } from 'react';

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

    static getDerivedStateFromError(error) {
        // Update state so the next render will show the fallback UI
        return { hasError: true };
    }

    componentDidCatch(error, errorInfo) {
        // You can also log the error to an error reporting service
        console.log(error, errorInfo);
    }

    render() {
        if (this.state.hasError) {
            // You can render any custom fallback UI
            return <h1>Something went wrong.</h1>;
        }

        return this.props.children;
    }
}

export default ErrorBoundary;
                

Using an Error Boundary

To use an error boundary, wrap any components that you want to catch errors in with the ErrorBoundary component.


// src/App.js
import React from 'react';
import ErrorBoundary from './components/ErrorBoundary';
import MyComponent from './components/MyComponent';

function App() {
    return (
        <div>
            <ErrorBoundary>
                <MyComponent />
            </ErrorBoundary>
        </div>
    );
}

export default App;
                

Example: Error Handling in a Component

Here is an example of a component that throws an error, and how it is handled by the error boundary.


// src/components/MyComponent.js
import React from 'react';

class MyComponent extends React.Component {
    componentDidMount() {
        throw new Error('An error occurred!');
    }

    render() {
        return <div>This is my component.</div>;
    }
}

export default MyComponent;

// src/App.js
import React from 'react';
import ErrorBoundary from './components/ErrorBoundary';
import MyComponent from './components/MyComponent';

function App() {
    return (
        <div>
            <ErrorBoundary>
                <MyComponent />
            </ErrorBoundary>
        </div>
    );
}

export default App;
                

Best Practices

Here are some best practices for using error boundaries in your React applications:

  • Use error boundaries to catch errors in specific parts of your component tree.
  • Do not use error boundaries for every component; instead, wrap higher-level components to catch errors in their subtree.
  • Provide a user-friendly fallback UI to indicate that an error occurred.
  • Log errors to an error reporting service for better debugging and monitoring.
  • Use error boundaries along with other error handling techniques for a comprehensive error management strategy.

Summary

In this tutorial, you learned about handling errors with error boundaries in React. Error boundaries catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the whole application. By creating and using error boundaries, you can handle errors gracefully and improve the user experience of your React applications.