Lesson 6 — React Router and lazy routes¶
Objective¶
Add static-host-safe routes for dashboard, topics, detail, and practice workflows.
Prerequisites¶
Lesson 5 — Context and dependency boundaries. You should understand how to provide state through a focused Context.
Mental Model¶
A route maps URL state to UI. Nested layouts preserve shared structure; lazy imports split implementation chunks. Hosting constraints are part of route design.
Concept¶
URL is state. A router chooses which component to render based on the URL path, history, and parameters. Lazy loading delays loading route code until the user needs it. Hash routing avoids server-side history support that static hosts may not provide.
Example¶
const router = createHashRouter([
{
path: '/',
element: <Layout />,
children: [
{ index: true, element: <Dashboard /> },
{ path: 'topics/:topicId', element: <TopicDetail /> },
{ path: '*', element: <NotFound /> },
],
},
]);
Real-World Usage¶
Multi-page SPAs, admin consoles, and documentation sites where sections are loaded on demand and deep links must survive refreshes.
Common Mistakes¶
- Using browser history on a host that does not support fallback routing.
- Splitting routes too finely, producing too many small chunks.
- Putting loading states only at the route level and leaving no Suspense boundary.
Mini Lab¶
Task¶
Configure HashRouter, lazy page imports, Suspense fallback, parameters, active links, and a fallback redirect. Synchronize meaningful document titles.
Constraints¶
- Navigate with links, browser back/forward, a missing topic ID, and an unknown URL.
- Build and test the artifact under
/react_vite_tutorial/.
Expected Result¶
All reachable URLs render the correct page, unknown URLs show a fallback, and the production build works on the configured base path.
Hints¶
Hash routing avoids GitHub Pages history fallback requirements. Keep route-level lazy boundaries coarse enough to produce useful chunks.
Knowledge Check¶
- Hash router versus browser router: what is the operational tradeoff?
- Where should loading and error boundaries live?
- What state belongs in the URL?
Challenge¶
Your app is moving from GitHub Pages to a proper origin server. What would need to change to switch to browser history, and what server behavior must you guarantee?
Summary¶
Routes are URL-to-UI mappings. Pick hash or browser history based on hosting constraints, and split code at meaningful route boundaries.