How to use error boundary using Hooks in React

In this post we are going to learn about the how to use error boundary using Hooks in React. Error Boundary are easy to use with class components using static getDerivedStateFromError() and componentDidCatch() lifecycle methods. But when its comes to hooks we can’t depend on lifecycle methods.

What is Error Boundary ?

Error boundaries are nothing but a simple React component which catch any JavaScript error in there child tree, log the error and display a custom fallback UI instead of displaying old component tree on the web page.

Error boundaries can catch error from these places

  • Render method.
  • Lifecycle methods.
  • Constructor method.

Error Boundary in Class Components

You can easily use error boundary in class components using the lifecycle methods. I have also written an article on that you can read that here.

For using the error boundary with class components we will create a ErrorBoundary Component which gonna have only one life cycle method i.e static getDerivedStateFromError() and it will gonna set a error state to true in case any error found and we can display our custom error boundary UI.

Error Boundary in Functional Components using hooks

Using the error boundary in functional components using the hooks is a little bit tricky because we can’t directly use life cycle methods in functional components. To handle this problem we have two solutions.

The first solution is that we can wrap our functional component with a class component which is pretty straight forward.

The second solution is that what if we don’t want to rely on the class components. In that case we can use a 3rd party package for that i.e use-error-boundary.


npm i use-error-boundary


// Named
import { useErrorBoundary } from "use-error-boundary"
// Default
import useErrorBoundary from "use-error-boundary"

You can extract four items from the useErrorBoundary.

const MyComponent = () => {
  const {
    ErrorBoundary, // class - The react component to wrap your children in. This WILL NOT CHANGE 
    didCatch, // boolean - Whether the ErrorBoundary catched something
    error, // null or the error
    errorInfo // null or the error info as described in the react docs
  } = useErrorBoundary()

You can use this package using two ways

Method 1

const JustRenderMe = () => {
  throw new Error('💥')
const MyComponent = () => {
   * The ErrorBoundary renders its children directly,
   * when a component throws, the ErrorBoundary will return null from its render method.
  return (
      <JustRenderMe />

Method 2

 * The renderError function also passes the error, so that you can display it using
 * render props.
return (
    render={() => <SomeChild />}
    renderError={({ error }) => <MyErrorComponent error={error} />}

That’s it. I hope you have learned how to use error boundary using Hooks in React.


Categories: Reactjs