Error Boundaries
- React
A React component that catches rendering errors in the subtree below it and shows a fallback UI, so one broken component does not crash the whole app.
Prerequisites
- Conditional rendering and error handling (see Related Topics)
What you'll understand
- What an error boundary protects against
- How a fallback UI keeps the rest of the app alive
- What error boundaries do and do not catch
Explanation
An error boundary is a component that catches JavaScript errors thrown while rendering the components beneath it, and displays a fallback UI instead of letting the error propagate. Without one, an uncaught error during rendering unmounts the entire React tree: the whole app goes blank. Error boundaries contain the damage to a section of the interface.
The idea mirrors error handling on the server (see Related Topics): a central place that catches unexpected failures, logs the detail, and returns something safe rather than crashing. You wrap a part of the tree in an error boundary, and if any component inside it throws during render, the boundary shows a fallback, an apology message, a retry button, while everything outside the boundary keeps working normally.
It is important to know the limits. Error boundaries catch errors during rendering, in lifecycle logic, and in constructors of the tree below them. They do not catch errors inside event handlers, asynchronous code like a fetch callback, or the boundary’s own code, because those do not happen during React rendering. Those cases you handle with ordinary try/catch and by tracking error state, as in data fetching.
Examples
You wrap a risky part of the tree so a failure there shows a fallback instead of crashing the app:
<ErrorBoundary fallback={<p>Something went wrong.</p>}>
<Dashboard />
</ErrorBoundary>Errors in event handlers or async code are not caught by boundaries; handle those explicitly:
try {
await saveChanges();
} catch (err) {
setError('Could not save'); // handled in state, not by a boundary
}Common mistakes
- Expecting an error boundary to catch errors in event handlers or async callbacks.
- Wrapping the entire app in one boundary, so any error still blanks everything.
- Showing a fallback but never logging the underlying error.
- Leaving no way for the user to recover, such as a retry.
Best practices
- Place boundaries around meaningful sections so a failure is contained.
- Show a helpful fallback and log the real error for diagnosis.
- Handle event-handler and async errors with try/catch and error state (see Related Topics).
- Offer a way to recover, like retrying or navigating away.
Further reading
- React, Catching rendering errors with an error boundary — https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary