Lesson 8 of 10
Error Boundaries in Routing
React Router v6.4+ allows declaring errorElement per route - when a loader, action, or component throws, React Router renders the errorElement instead. This enables granular error handling: a section of the page can show an error without crashing the entire app.
Route Error Handling
import { useRouteError, isRouteErrorResponse, Link } from 'react-router-dom';
// ErrorBoundary component - used as errorElement
function RouteError() {
const error = useRouteError();
// React Router throws Response objects for non-2xx HTTP responses
if (isRouteErrorResponse(error)) {
if (error.status === 404) {
return (
<div className="error-page">
<h1>404 - Page Not Found</h1>
<p>The page you're looking for doesn't exist.</p>
<Link to="/">Go Home</Link>
</div>
);
}
if (error.status === 403) {
return <div>You don't have permission to access this page.</div>;
}
return <div>HTTP Error {error.status}: {error.statusText}</div>;
}
// JavaScript Error thrown during render or loader
if (error instanceof Error) {
return (
<div className="error-page">
<h1>Something went wrong</h1>
<p>{error.message}</p>
<button onClick={() => window.location.reload()}>Reload</button>
</div>
);
}
return <div>An unexpected error occurred</div>;
}
// Router config - errorElement as granular boundary
const router = createBrowserRouter([
{
path: '/',
element: <RootLayout />,
errorElement: <RouteError />, // catches errors from any child if they don't have their own
children: [
{
path: 'dashboard',
element: <DashboardLayout />,
loader: dashboardLoader,
errorElement: <DashboardError />, // only catches errors from this route's loader/component
children: [
{
path: 'reports',
element: <Reports />,
loader: reportsLoader,
errorElement: <ReportsError />, // most specific boundary wins
},
],
},
],
},
]);Tip
Tip
Practice Error Boundaries in Routing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Error Boundaries in Routing
Practice Task
Note
Practice Task - (1) Write a working example of Error Boundaries in Routing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Error Boundaries in Routing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Finished this lesson?