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>
  )
}
const ui = (
  <ErrorBoundary
    FallbackComponent={ErrorFallback}
    onReset={() => {
      // reset the state of your app so the error doesn't happen again
    }}
  >
    <ComponentThatMayError />
  </ErrorBoundary>
)

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.

32