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.

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

import {ErrorBoundary} from 'react-error-boundary'

function ErrorFallback({error, resetErrorBoundary}) {
  return (
    <div role="alert">
      <p>Something went wrong:</p>
      <button onClick={resetErrorBoundary}>Try again</button>
Enter fullscreen mode Exit fullscreen mode
const ui = (
    onReset={() => {
      // reset the state of your app so the error doesn't happen again
    <ComponentThatMayError />
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

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)