Company
Date Published
Author
Max Bittker
Word count
1127
Language
English
Hacker News points
None

Summary

React 16 introduces a new tool called error boundaries to handle errors with a more correct and rigorous strategy by unmounting the entire component tree when errors are thrown inside render or lifecycle methods, preventing situations where an error causes invalid state and results in undefined behavior. Error boundaries are analogous to try/catch statements but live inside and are scoped by component hierarchy instead of inside a given block of synchronous JavaScript. They exist because this approach doesn't work with the JSX rendering model. By using error boundaries, developers can isolate sections of their app's component tree from each other's errors, improving error resiliency without sacrificing React 16's more predictable behavior and risking corrupted state or undefined behavior. The API surface of error boundaries is simple, requiring any React component to implement the new lifecycle method, componentDidCatch(error, info), which will be called with uncaught errors that bubble up from children's lifecycle methods, constructors, or render methods. When an error is caught, developers can do whatever they see fit, but must replace rendered props.children with a fallback UI and ensure it doesn't throw its own errors. Error boundaries should be wrapped at the granularity they can be independently useful, protecting certain components from being unmounted on an error while giving users an easy way to back out and return to working parts of the application. Developers should also send errors to Sentry for insights and fix them.