Basic Routing with React Router
On this page
Routing as State
- The current route is a state machine for the whole app.
- Route changes trigger remounts depending on layout and boundary design.
- Production routing requires explicit handling for 404, unauthorized, and error states.
Route Boundaries
- Define which parts of the UI are stable across navigation (layout shell).
- Keep long lived UI state in stable parents when it must survive navigation.
- Do not assume component state survives a route change.
Data Loading Strategy
- Decide per route: load on navigation, load in component, or prefetch.
- Prevent waterfalls by centralizing critical route data loading.
- Handle loading, error, empty, and ready per route.
Auth and Guarding
- UI guards improve UX but server must enforce authorization.
- Use route level guards for private areas.
- Handle token expiry and refresh failures predictably.
Operational Requirements
- Deep links must work with server configuration.
- Back and forward navigation must preserve expected state.
- Scroll restoration must be defined for long pages.
Example: Basic Router Structure
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
function RequireAuth({ authed, children }) {
if (!authed) return <Navigate to="/login" replace />;
return children;
}
export function App({ authed }) {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route
path="/app"
element={
<RequireAuth authed={authed}>
<AppShell />
</RequireAuth>
}
/>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
}
Failure Modes
- Broken deep links when the server does not route all paths to the SPA entry point.
- Unexpected remount resets when route boundaries change or keys change.
- Navigation loops from guards that redirect repeatedly on transient auth state.
- Waterfall fetches from scattered data loading across nested components.
- State loss for in progress forms or filters due to route changes.
Incident Triage Checklist
- Does a direct refresh on a deep route work in production?
- Are redirects stable or do they loop?
- Is state loss explained by route boundary remounting?
- Is route data loading centralized to avoid waterfalls?
Deployment Notes
- SPA servers must rewrite unknown routes to index.html.
- CDN caching must not cache index.html incorrectly for authenticated areas.