2

What kind of errors does it handle, and is there any real-world scenario?

I read the docs but it doesn't give a good example.

And docs also mention it handles UI errors, but UI errors can be solved at development time, so exactly why do we need "Error Boundaries".

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Aady
  • 56
  • 1
  • 7

2 Answers2

1

but UI errors can be solved at development time

UI errors can't be solved at development time, although typing like Flow & Typescript indeed help a lot, still, there may be run-time errors that usually come for the data server.


Error Boundaries used for catching run time errors and displaying a friendly UI.

See Compile time vs Run time errors.

ErrorBoundary is a class components that implements getDerivedStateFromError and componentDidCatch in order to add additional render on fall back UI.

Currently, it can only be implemented with a class component, typically its the only class component in your application, the rest is function components with hooks.

In real-life use cases, you wrap your application with some <ErrorBoundary/> component and render the desired UI.

class ErrorBoundary extends React.Component {
  state = {
    hasError: false,
    error: { message: '', stack: '' },
    info: { componentStack: '' }
  };

  static getDerivedStateFromError = error => {
    return { hasError: true };
  };

  componentDidCatch = (error, info) => {
    this.setState({ error, info });
  };

  render() {
    const { hasError, error, info } = this.state;
    const { children } = this.props;

    return hasError ? <ErrorComponent/> : children;
  }
}

<ErrorBoundary>
  <App/>
</ErrorBoundary>

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
1

Error Boundaries are like try-catch blocks for react components . They allow you to catch and handle unexpected errors in react components gracefully, for example, display a message to the user that something went wrong.

These errors, if not handled will crash your app. Error boundaries allow you to catch those errors and handle them in a way that prevents your app from crashing and instead provide a user friendly message to the user indicating that something went wrong.

Keep in mind that Error Boundaries do not handle errors for:

  • Event handlers
  • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself (rather than its children)

Here's a nice article that explains error boundaries

Yousaf
  • 27,861
  • 6
  • 44
  • 69