Member-only story
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);
}