How to implement error boundaries in React Js
- Get link
- X
- Other Apps
Error boundaries in React Js
In this post, we will learn about "Error Boundaries in React Js". First of all, why we required Error Boundaries? This is the first question comes in my mind, as before React 16, we don't have any mechanism to catch error inside components and because of which whole app in broken state on next renders. No ways to handle these errors in React Components, nor it gives any methods to recover from them.
React 16 introduces a new concept to handle such errors by using the error boundaries. So now, if any error found in a part of the UI, it does not break the whole application.
According to official document of React Js, There are following few areas in application, where error boundaries are not suitable solution.
a) Event handlers
b) Asynchronous code (e.g., setTimeout)
c) Server-side rendering
d) Errors are thrown in the error boundary itself
For complex application which contains multiple components, we can declare multiple error boundaries to recover each part of the entire application.
Error Boundaries Class Component contains following important things:
a) getDerivedStateFromError() - It is static method to render a fallback UI when an error has been thrown,
b) componentDidCatch() - to log error information.
Implementation of error boundaries:
a) Create a class which extends React component and passes the props inside it.
b) Add componentDidCatch() method which allows you to catch error in the components below them in the tree
c) Add render() method, it will display the error message or render new component.
d) Now, we can use it as a regular component. Add the new component in HTML, which you want to include in the error boundary. In this example, we are adding an error boundary around a App Component.
<ErrorBoundary>
<App />
</ErrorBoundary>
Where to place Error Boundaries:
a) It depends on us. we can use error boundaries on the top level of the app components
b) or wrap it on the individual components.
Sample Code:
A) index.js
B) App.js
C) ErrorBoundary.js
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments
New comments are not allowed.
Nice Content thanks for sharing about error in reac js
ReplyDeleteWeb Development Company Dubai