Error boundaries
Keep a render-time failure inside one subtree, and recover from it without a full page reload.
- #react
- #patterns
- #error-handling
A boundary catches an error thrown while its subtree renders and shows a fallback, instead of unmounting the whole application.
Implementation
What boundaries do not catch
- An error thrown in an event handler. That reaches
window.onerrorinstead. - A rejected promise outside a
useor Suspense read. - An error during server rendering, which the framework handles itself.
Placement
One boundary at the root gives a whole-page fallback, which tells the reader nothing and loses the rest of the page. Put a boundary on each seam the UI already has: a panel, a route segment, a widget that loads on its own.
Related entries
- Type-safe result pattern. Return an error value instead of throwing, for a failure you expect.
- Toast notification stack. Reports a recoverable error without unmounting the subtree.
Related entries
Compound components
Expose a component's internals as named subcomponents that share state through a private context.
Render props
Hand rendering control to the caller through a function child, and when a hook is the better answer.
useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.