DEV Community

Cover image for React Hooks can ALMOST do Everything Class Components Can Do... ALMOST!
Philip John Basile
Philip John Basile

Posted on • Updated on

React Hooks can ALMOST do Everything Class Components Can Do... ALMOST!

In the React world, "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. Unfortunately, Error Boundaries cannot be implemented with Hooks, but only with class components. The React team has promised a hooks variation, but its been years since the initial promise was made.

If you would like to use a workaround to implement something similar to Error Boundaries using Hooks, here's a possible way to do it using a Higher Order Component (HOC). This HOC wraps a functional component and gives it similar functionality to an error boundary.

First, you need to create a HOC as an error boundary:

import React from 'react';

function withErrorBoundary(WrappedComponent) {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {
      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 <WrappedComponent {...this.props} />;
    }
  }
}

export default withErrorBoundary;
Enter fullscreen mode Exit fullscreen mode

Then, you can use this HOC to wrap your functional components, providing them with error boundary functionality:

import React from 'react';
import withErrorBoundary from './withErrorBoundary';

function SomeComponent() {
  // ... component implementation ...
}

export default withErrorBoundary(SomeComponent);

Enter fullscreen mode Exit fullscreen mode

Remember, this is just a workaround and has some limitations compared to true Error Boundaries. For instance, it won't catch errors in event handlers. Using class components for Error Boundaries is the recommended approach in React. Please refer to the latest React documentation or community resources for the most recent practices.

Catching rendering errors with an error boundary

If you enjoy my technology-focused articles and insights and wish to support my work, feel free to visit my Ko-fi page at https://ko-fi.com/philipjohnbasile. Every coffee you buy me helps keep the tech wisdom flowing and allows me to continue sharing valuable content with our community. Your support is greatly appreciated!

Top comments (0)