DEV Community

Cover image for Error boundaries in React
Samuel Lucas
Samuel Lucas

Posted on

2

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay