DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Error boundaries in React
Samuel Lucas
Samuel Lucas

Posted on

Error boundaries in React

Hello my dear reader, enjoy your stay reading today's content.

Let begin with knowing what error boundaries are. Simply, they are react components that catch errors from your code, log them and display the UI you set for error(fallback).

How can this be of help to you?
Whenever you have a break(πŸ’”) in your UI, this helps discover it and effect an action immediately. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
For example, Facebook Messenger wraps content of the sidebar, the info panel, the conversation log, and the message input into separate error boundaries. If some component in one of these UI areas crashes, the rest of them remain interactive.

Read more on error boundary on the react official website. https://reactjs.org/docs/error-boundaries.html

How do you use it?
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>
  )
}
Enter fullscreen mode Exit fullscreen mode
const ui = (
  <ErrorBoundary
    FallbackComponent={ErrorFallback}
    onReset={() => {
      // reset the state of your app so the error doesn't happen again
    }}
  >
    <ComponentThatMayError />
  </ErrorBoundary>
)
Enter fullscreen mode Exit fullscreen mode

Good news is this just the tip of an iceberg, read the full docs to see more awesome features
https://www.npmjs.com/package/react-error-boundary

There we have it for this trick and tips in React hooks.

If this blog post helps, kindly give it a like and share. Thanks.

Top comments (0)

πŸ‘‹ Hey, my name is Noah and I’m the one who set up this ad. My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.

If you found DEV from searching around, here are a couple of our most popular articles on DEV: