How can we implement error Boundary in React Hooks. Is it even supported with react Hooks?
7 Answers
The questions is whether it is possible to implement Error Boundary as a hook and the answer is no BUT it does not mean that you can not use Error Boundary class components in a project which you use hooks heavily.
Create a Error Boundary class component and wrap your React Functional Components(hooks) with the Error Boundary class component.
3 Comments
Renedered fewer hooks than expected error for me, because the hooks are behind a conditional statement.You can implement error boundary in react hooks with the help of react-error-boundary package.
npm install --save react-error-boundary
Then:
import {ErrorBoundary} from 'react-error-boundary'
function ErrorFallback({error, resetErrorBoundary}) {
return (
<div role="alert">
<p>Something went wrong:</p>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
)
}
const ui = (
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => {
// reset the state of your app so the error doesn't happen again
}}
>
<ComponentThatMayError />
</ErrorBoundary>
)
Please read more on React-error-boundary
1 Comment
*There is no Error Boundaries in hook yet *
componentDidCatch
and
getDerivedStateFromError
There are no Hook equivalents for these methods yet, but they will be added soon.
3 Comments
I wrote react-use-error-boundary to achieve this.
React 16 introduced Error Boundaries. As of React 17, there still is not an equivalent hook for function components.
I liked the API implemented by Preact's useErrorBoundary and attempted to recreate a similar API. If you're interested in building this from scratch you can checkout the code on GitHub.
Comments
You can't do that with hooks. Hooks do not have an equivalent of componentDidCatch. See this section of the hook FAQ
getSnapshotBeforeUpdate,componentDidCatchandgetDerivedStateFromError: There are no Hook equivalents for these methods yet, but they will be added soon.
1 Comment
componentDidCatch. In the FAQ they don't refer to 'Error Boundaries', all other answers here are assuming you know Error Boundaries means componentDidCatch.For React v18.3.1 and above.
Replace AddCommentButton with App component.
import { useTransition } from "react";
import { ErrorBoundary } from "react-error-boundary";
export function AddCommentContainer() {
return (
<ErrorBoundary fallback={<p>⚠️Something went wrong</p>}>
<AddCommentButton />
</ErrorBoundary>
);
}
function addComment(comment) {
// For demonstration purposes to show Error Boundary
if (comment == null) {
throw new Error("Example Error: An error thrown to trigger error boundary");
}
}
function AddCommentButton() {
const [pending, startTransition] = useTransition();
return (
<button
disabled={pending}
onClick={() => {
startTransition(() => {
// Intentionally not passing a comment
// so error gets thrown
addComment();
});
}}
>
Add comment
</button>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
Comments
how about this:
import React, { useState, useEffect } from 'react';
function ErrorBoundary(props) {
const [error, setError] = useState(null);
useEffect(() => {
// Catch errors thrown by child components
const handleErrors = (err) => {
setError(err);
};
window.addEventListener('error', handleErrors);
return () => {
window.removeEventListener('error', handleErrors);
};
}, []);
if (error) {
return <h1>Something went wrong: {error.message}</h1>;
}
return props.children;
}
export default ErrorBoundary;
2 Comments
window.addEventListener('error', ...) doesn't catch uncaught errors, read about what it's actually for developer.mozilla.org/en-US/docs/Web/API/Window/error_event.