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>
}
})
i tried it works great how but it should reset the state of error if click on something and it takes me to a new route how can i do that i tried to see where can i do it but couldnt find any appropriate place