Skip to main content

Command Palette

Search for a command to run...

Handle Child Components Error States using Error Boundaries

Updated
3 min read
Handle Child Components Error States using Error Boundaries

Overview

React sub-components helps to organize and enhance code quality. By applying, React component hierarchy principles, we can have better code structure and improve the reusability of components, but sometimes this can lead to some crashes, due to problematic JavaScript code, invalid API usage, inconsistent flow, etc. These small, unexpected inconsistencies can crash the whole app, which is the least expected behavior by a user from any app. To handle these errors gracefully, React introduced error boundaries components.

Error boundaries provide a convenient way to log errors while displaying a fallback UI to inform the users about the possible issue. This guide will cover the implementation of error boundaries to handle errors in the React UI hierarchy with pro tips.

Setting up Error Boundary Component

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

A component can simply be converted into an error boundary component by defining either static getDerivedStateFromError(error) or componentDidCatch(error, errorInfo)

import React, { Component } from 'react';

export default class ErrorBoundary extends Component {

    state = { hasError: false };

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

    componentDidCatch(error, info) {
        // logging the error details
        console.log(`Cause: ${error}.\nStackTrace: ${info.componentStack}`);
    }

    render() {
        if (this.state.hasError) {
            // Return the fallback UI
            return <h3 style={{ 'text-align': 'center' }}>Unfortunately, something went wrong.</h3>;
        }

        return this.props.children;
    }
}

The difference between getDerivedStateFromError and componentDidCatch methods are based on:

LifeCycle

The getDerivedStateFromError is called during the render phase to update the state so that the fallback UI can be rendered as per the updated hasError value from the state object. On the other side, componentDidCatch is called during the commit phase that occurs after the render phase, so the ideal place to update the state is getDerivedStateFromError method.

Parameter

As you may have observed, componentDidCatch provides an additional info object that can be used to fetch the error stack-trace for logging purposes.

UseCase

Since the getDerivedStateFromError is called during the render method, and the rendering phase is often slower than the commit phase, it's recommended to use componentDidCatch for error details processing and logging tasks.

Error Boundary implementation

The sole purpose of error boundaries is to handle the error during the execution of any lifecycle or render function of any nested subcomponent. Error boundaries do not handle errors from event-handlers, asynchronous code (Promise, fetch, etc.), and SSR (server-side rendering). Instead, a try-catch block should be used to handle errors in event-handlers or in any asynchronous task (e.g. Promises, setInterval, requestAnimationFrame, etc.). The major differences between error boundaries and try-catch are:

Rendering Error

Try-catch should be used to handle any potential issues that can occur due to invalid input/data, connection issues or bad server response, etc.

try{
    var response = getBooksFromStoreAPI();
 } catch(e){
    console.log('error', e);
}

The getBooksFromStoreAPI() may throw an error because of invalid response or bad connection, which will be handled by the try-catch block.

Tips

  • UI can be divided into sections and use different error boundary components for each section to keep most of the app running smoothly.

  • Manage a boolean flag in state to display the fallback error UI. Additionally, state can store the error message details that can be used to inform users about the issue.