36. Error Boundaries
Catching UI Crashes
In standard JavaScript, if a function throws an error, you wrap it in a try...catch block. However, you cannot wrap a React component's JSX in a try...catch block. If a component tries to map over a null array, it crashes. In React, if one component crashes, the entire application unmounts, leaving the user with a completely blank "White Screen of Death". We prevent this using Error Boundaries.
What is an Error Boundary?
An Error Boundary is a React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the whole component tree. It acts exactly like a catch {} block, but for components.
The `react-error-boundary` Library
Historically, Error Boundaries had to be written using Class Components (using the componentDidCatch lifecycle method). Today, the modern standard is to use the lightweight react-error-boundary library, which provides a clean, functional approach.
Where to Place Error Boundaries
You should place Error Boundaries strategically. You want one at the very top of your app (to catch fatal router errors), but you also want them wrapping individual "Widgets" or "Features". If a single widget on a Dashboard crashes, only that widget should show an error box; the rest of the Dashboard should remain fully usable.
Knowledge Check
Ready to test your understanding of 36. Error Boundaries?