Have you ever faced a problem where one error will crash whole the app.
In Reactjs if a component got an error then by default component tree of the error is displayed on the web page to display a custom fallback UI Reactjs introduced the concept of error boundaries .
What is error boundaries
Error boundaries can catch error from these places
- Render method.
- Lifecycle methods.
- Constructor method.
Error boundaries can not catch error from these places
- Error thrown in Error boundary component itself instead of there child.
- Server side rendering (SSR)
- Async code i.e setTimeout etc
- Event Handlers
How to use Error Boundary in Reactjs
Any Component which can have either one or both of the lifecycle methods. Those lifecycle methods are:
We will create a ErrorBoundary Component which gonna have only one life cycle method i.e
static getDerivedStateFromError() and it will gonna set a error state to true in case any error found and we can display our custom error boundary UI.
Example of error boundary
We gonna wrap our ErrorBoundary Component to our wrap App so that we can catch error.
To see the fallback UI we gonna create an error manually in our App.
Now we can see a custom fallback UI instead of the component tree.
In case you are using react-create-app you are going to see a overlay of error stack in development mode on top of fallback UI.
Checkout best UI library for React here.