How to implement Error Boundary with React Hooks Component

Reactjs

Reactjs Problem Overview


How can we implement error Boundary in React Hooks. Is it even supported with react Hooks?

Reactjs Solutions


Solution 1 - Reactjs

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.

Solution 2 - Reactjs

***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.

Solution 3 - Reactjs

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

Solution 4 - Reactjs

You can't do that with hooks. Hooks do not have an equivalent of componentDidCatch. See this section of the hook FAQ

Solution 5 - Reactjs

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarish DhamiView Question on Stackoverflow
Solution 1 - ReactjsEfeView Answer on Stackoverflow
Solution 2 - ReactjsAsgar Ali KhachayView Answer on Stackoverflow
Solution 3 - ReactjsVictor KarangwaView Answer on Stackoverflow
Solution 4 - ReactjsNicholas TowerView Answer on Stackoverflow
Solution 5 - ReactjsTate ThurstonView Answer on Stackoverflow