Error Boundary là class component bắt lỗi trong lúc render của cây con, hiển thị fallback UI thay vì sập cả app (React unmount toàn bộ tree nếu lỗi không được bắt). Nó bắt qua static getDerivedStateFromError (cập nhật state để render fallback) và componentDidCatch (log).
Vì sao hook không bắt được lỗi render: try/catch chỉ bắt code chạy đồng bộ trong phạm vi của nó. Quá trình render do React điều phối, không nằm trong try/catch của bạn; React phải tự phát hiện lỗi rồi bubble lên boundary gần nhất. Hiện chưa có hook API tương đương — cơ chế này chỉ tồn tại ở class lifecycle, nên Error Boundary phải là class.
react-error-boundary (bvaughn) bọc lại bằng API tiện cho hooks-era:
- <ErrorBoundary FallbackComponent={...} onReset={...}> với nút "thử lại".
- useErrorBoundary() để ném thủ công lỗi async (event handler, promise) vào boundary — vì những lỗi này boundary không tự bắt.
Error Boundary KHÔNG bắt: lỗi trong event handler, code async (setTimeout, fetch), SSR, và lỗi ném từ chính boundary đó. Những case này tự try/catch hoặc dùng showBoundary() để chuyển vào boundary.
An Error Boundary is a class component that catches errors during render of its subtree, showing a fallback UI instead of crashing the whole app (React unmounts the entire tree on an uncaught error). It catches via static getDerivedStateFromError (set state to render fallback) and componentDidCatch (log).
Why a hook can't catch render errors: try/catch only catches code running synchronously in its scope. Rendering is orchestrated by React, not inside your try/catch; React itself must detect the error and bubble it to the nearest boundary. There's no equivalent hook API — this mechanism only exists in class lifecycle, so an Error Boundary must be a class.
react-error-boundary (by bvaughn) wraps this with a hooks-era API:
- <ErrorBoundary FallbackComponent={...} onReset={...}> with a "try again" button.
- useErrorBoundary() to manually throw async errors (event handlers, promises) into the boundary — those it won't catch on its own.
Error Boundaries do NOT catch: errors in event handlers, async code (setTimeout, fetch), SSR, and errors thrown by the boundary itself. Handle those with your own try/catch or showBoundary() to forward into the boundary.