Thanks to React hooks you have now happily turned all your classes into functional components.
Wait, all your components? Not quite. There is one thing that can still only be implemented using classes: Error boundaries.
There is just no functional equivalent for componentDidCatch
and deriveStateFromError
yet.
The proposed solution is greatly inspired by the new React.memo()
API.
import Catch from "./functional-error-boundary"
type Props = {
children: React.ReactNode
}
const MyErrorBoundary = Catch(function MyErrorBoundary(props: Props, error?: Error) {
if (error) {
return (
<div className="error-screen">
<h2>An error has occured</h2>
<h4>{error.message}</h4>
</div>
)
} else {
return <React.Fragment>{props.children}</React.Fragment>
}
})
type ErrorHandler = (error: Error, info: React.ErrorInfo) => void
Wraps the functional component component
to make it an error boundary.
The caught error is passed to the component
function as a second parameter.
The optional second argument to Catch()
(errorHandler
) is a function that acts as componentDidCatch()
. Use it to handle side effects like error logging.
Find the code below.
Would be great to see something like this integrated into the React.js core library:
import React from "react"
type Props = {
children: React.ReactNode
}
const MyErrorBoundary = React.Catch(function MyErrorBoundary(props: Props, error?: Error) {
if (error) {
return (
<div className="error-screen">
<h2>An error has occured</h2>
<h4>{error.message}</h4>
</div>
)
} else {
return <React.Fragment>{props.children}</React.Fragment>
}
})
๐