Home / Learn React / Error Boundaries
Error Boundaries
If one component crashes while rendering, you do not want the whole page to go blank. An error boundary catches the error and shows a safe message for that part.
Theory in plain words
What it is
An error boundary is a component that catches JavaScript errors thrown while rendering its children, and shows a fallback UI instead of crashing the whole tree.
Why we use it
Since React 16, an uncaught render error unmounts the entire app, leaving a blank white page. Boundaries keep the rest of the page alive and give you a place to log the error.
How it works
A class with static getDerivedStateFromError(error) returns new state that triggers the fallback. componentDidCatch(error, info) logs it. Boundaries do not catch errors in event handlers, async code or the boundary itself.
Where it is used
- Around widgets, routes and third party components
- Reporting errors to Sentry or a log
- A "Try again" button that resets the section
What boundaries do not catch
- Errors in event handlers: use
try / catchthere. - Errors in
setTimeoutor promises: catch them and put the error in state (or throw it in render from state). - Errors during server side rendering and errors in the boundary itself.
npm install react-error-boundary
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary FallbackComponent={Oops} onReset={() => refetch()}>
<Dashboard />
</ErrorBoundary>onCaughtError, onUncaughtError and onRecoverableError to createRoot so you can log all errors in one place.Quick quiz
1. What does an error boundary catch?
Render, lifecycle and constructor errors of the tree below.
2. How do you write an error boundary yourself?
Boundaries still need a class (or the react-error-boundary library).
3. Where do you handle errors inside onClick?
Boundaries do not catch event handler errors.
Common questions
What does an error boundary catch?
Errors while rendering its children. Render, lifecycle and constructor errors of the tree below.
How do you write an error boundary yourself?
A class with getDerivedStateFromError. Boundaries still need a class (or the react-error-boundary library).
Where do you handle errors inside onClick?
try / catch in the handler. Boundaries do not catch event handler errors.