If you have built a React app at any point in your programming career, you probably have experienced an error at some point that was cryptic and did not provide any meaningful context on what actually happened.
That meant error occured at some point in the application and our React component did not handle the error gracefully.
try/catch only works for imperative code, but React components are declarative.
Since early React development (≤15), it was common for a child component throwing an error to break the entire application and React did not provide a way to handle them gracefully in components. That’s why Error Boundaries are a good thing.
Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
In React 16 we have a built-in function called componentDidCatch to deal with this uncaught errors. Let’s take a look:
Error Boundaries in React
🧐 First all, important to know that Error Boundaries will not catch errors in:
- Event handlers. ** — Use a
try / catchblock instead within event handlers.
- Asynchronous code (e.g.
- Server side rendering
- Errors within the Error Boundary Component. — You cannot save others if you cannot save yourself first.
After that, let’s recall a new lifecycle method called
With error boundaries, even if one of your component’s results in an error, the entire react app would not get unmounted and instead only the erroneous component would display a fallback UI and the entire app would still be fully functional.