Introduction
Error boundaries catch mistakes in parts of your app so the whole app does not stop working.
Error boundaries catch mistakes in parts of your app so the whole app does not stop working.
export function ErrorBoundary({ error }) {
return (
<div role="alert">
<h2>Something went wrong.</h2>
<p>{error.message}</p>
<p>Please try again later.</p>
</div>
);
}export function ErrorBoundary({ error }) {
return <p>Oops! We hit a problem: {error.message}</p>;
}export function ErrorBoundary({ error }) {
return (
<div role="alert">
<h2>Error loading this page.</h2>
<p>{error.message}</p>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
);
}This route throws an error in the loader. Instead of crashing the app, the ErrorBoundary shows a friendly message.
import { useLoaderData } from "@remix-run/react"; export function loader() { throw new Error("Data failed to load"); } export default function MyRoute() { const data = useLoaderData(); return <div>Data: {data}</div>; } export function ErrorBoundary({ error }) { return ( <div role="alert"> <h2>Oops! Something went wrong.</h2> <p>{error.message}</p> <p>We could not load the data.</p> </div> ); }
Error boundaries only catch errors in their route or component subtree.
They do not catch errors in event handlers or asynchronous code outside React rendering.
Always provide a clear message so users know the app is still working.
Error boundaries stop errors from crashing the whole app.
They show fallback UI to keep users informed.
Use them to improve app stability and user experience.
ErrorBoundary that returns fallback UI.ErrorBoundary returning JSX fallback UI.export function ErrorBoundary() {
return <div>Oops! Something went wrong.</div>;
}
export default function Component() {
throw new Error('Crash');
return <div>Hello</div>;
}ErrorBoundary function returns fallback UI text 'Oops! Something went wrong.' which will display instead.export function ErrorBoundary() {
console.log('Error caught');
}Pass the test and this pattern moves unknown