Error Boundaries
Error boundaries are React components that catch JavaScript errors in their child component tree during rendering, in lifecycle methods, and in constructors. They display a fallback UI instead of crashing the whole app.
Error boundaries are safety nets at a circus — they catch performers (components) who fall during the act (rendering), but they can't help if someone trips backstage (event handlers).
Error boundaries are class components implementing static getDerivedStateFromError (to render fallback UI) and/or componentDidCatch (for error logging). They do NOT catch errors in event handlers (use try/catch), async code (use promise catch), SSR, or errors thrown in the boundary itself. Place them strategically: a top-level boundary prevents a white screen, granular boundaries isolate failures to specific widgets. You can reset an error boundary by changing its key prop.
There's no hook equivalent of error boundaries — they require class components (or a library like react-error-boundary that wraps the class). The react-error-boundary library provides a functional API with ErrorBoundary component, fallbackRender, onReset, and resetKeys. In React 19, error boundaries work with Suspense for server component errors — if a server component throws, the nearest error boundary catches it. Error boundaries pair well with Suspense: <ErrorBoundary fallback={<Error />}><Suspense fallback={<Loading />}><AsyncComponent /></Suspense></ErrorBoundary>.
Error boundaries catch rendering errors in the child tree and display fallback UI. They're class components — no hook equivalent exists yet, so I use the react-error-boundary library for a functional API. I place them at multiple levels: a top-level one for crash prevention and granular ones around risky widgets. They pair with Suspense to handle both loading and error states.
Expecting error boundaries to catch errors in event handlers or async code. They only catch errors during React's render and commit phases. Use try/catch for event handlers and .catch() for promises.