Skip to content

Latest commit

 

History

History
179 lines (120 loc) · 7.61 KB

File metadata and controls

179 lines (120 loc) · 7.61 KB

🚀 TanStack Router Crash Course

Before we dive into the details of the projects, please take a moment to support the project and the community:

  • 🎥 Subscribe to the tapaScript YouTube Channel for structured programming tutorials, web development deep-dives, and frontend/backend courses.
  • ⭐️ Star this Repository on GitHub to show your appreciation and help other developers find it!
  • 💖 Support & Sponsor the creator on GitHub Sponsors to keep open-source education free and sustainable.

🔥 The Tanstack Router Crash Course Video

tanstack-router-crash-course

📌 Repository Overview

This repository is a comprehensive, hands-on learning environment for mastering TanStack Router in React. It contains a full-stack structure split into two separate directories:

  1. meetup-mock-api: A mock backend REST API built using json-server to serve event database entries.
  2. meetup-tracker: A modern React 19 application showcasing core and advanced patterns of TanStack Router.

📁 Project Directory Structure

tanstack-router-crash-course/
├── meetup-mock-api/          # Mock REST API backend
│   ├── db.json               # JSON database file
│   └── package.json          # Server configuration
└── meetup-tracker/           # React 19 frontend app
    ├── src/
    │   ├── components/       # Shared UI components
    │   ├── routes/           # File-based routes & components
    │   ├── utils/            # Authentication & helpers
    │   ├── main.tsx          # App entrypoint & context injection
    │   └── router.tsx        # Router setup & TS register declarations
    ├── package.json          # Dependencies & scripts
    └── tsr.config.json       # TanStack Router configuration

🗄️ 1. Meetup Mock API (meetup-mock-api)

The meetup-mock-api project provides a lightweight, local mock REST API server that feeds event and meetup details to the React frontend application.

Tech Stack (Backend)

  • json-server: A tool to create a full mock REST API with zero coding.
  • Node.js & npm/pnpm: Package management.

Database & Data Model (db.json)

The database contains a list of events/meetups under the events collection. Each meetup object has the following schema:

  • id(string): Unique identifier (e.g., "react-kolkata").
  • title (string): The title/name of the meetup.
  • date (string): Date in YYYY-MM-DD format.
  • location (string): The venue or area hosting the event.
  • description (string): Detailed explanation of the event scope.
  • attendees (number): Number of RSVP'd attendees.
  • city (string): The host city (e.g., "Kolkata", "Bengaluru").
  • tech (string): Primary technology stack (e.g., "React", "Full-Stack").

Run the API

To launch the mock server on port 3001:

cd meetup-mock-api
pnpm install
pnpm start

🖥️ 2. Meetup Tracker (meetup-tracker)

The meetup-tracker project is a fully-featured frontend application showcasing the best routing mechanism available for the web today: TanStack Router. It contains practical examples ranging from simple routing to advanced concepts.

Tech Stack(Front-End)

  • React 19 & TypeScript
  • Vite: Frontend build system.
  • Tailwind CSS v4: Utility-first styles.
  • TanStack Router & TanStack Devtools: Fully type-safe file-based router.
  • Zod: Schema declaration and validation.
  • Vitest: Modern testing framework.

🌟 Key Routing Concepts Demonstrated

1. Router Initialization & Context (src/main.tsx, src/router.tsx)

  • Shows how to construct the router instance using createRouter and export it type-safely.

  • Demonstrates how to inject dependencies (like the auth helper object) globally into the routing context.

  • Declares the global typescript module expansion to register the router interface:

    declare module '@tanstack/react-router' {
      interface Register {
        router: typeof router
      }
    }

2. Root Layout & DevTools (src/routes/__root.tsx)

  • Uses createRootRouteWithContext to define a global wrapper context.
  • Provides the shared markup, header navigation, and the <Outlet /> element where active route pages are rendered.
  • Integrates the <TanStackDevtools /> and <TanStackRouterDevtoolsPanel /> plugins directly into the UI.

3. Static & Programmatic Routing (src/routes/index.tsx, src/routes/about.tsx)

  • Includes typical static routes like Home (/) and About (/about).
  • Demonstrates declarative navigation with <Link> components.
  • Demonstrates programmatic navigation via the useNavigate hook, triggering an automatic redirect when a counter button is clicked 3 times.

4. Dynamic Parameter Routing (src/routes/org/activities/meetups/$meetupId.tsx)

  • Uses dynamic route parameters ($meetupId).
  • The route loader grabs params.meetupId to request the corresponding event detail page from the mock server.
  • Specifies a custom pendingComponent to render skeleton states during fetching and an errorComponent to capture route failures.

5. Nested Layout Routing (src/routes/org/activities/meetups/route.tsx)

  • Demonstrates how parent layouts wrap nested paths (e.g. index.tsx, create.tsx, $meetupId.tsx) and inject a dashboard border and header.

6. Search Parameter Validation & Synchronization (src/routes/org/activities/meetups/index.tsx)

  • Validates URL search parameters (city and tech) using zod.
  • Uses loaderDeps to declare search dependencies, ensuring that changes to the URL's query parameters automatically trigger the route loader to filter meetups.
  • Updates search params using programmatic navigations to filter items cleanly without losing history state.

7. Code Splitting & Lazy Routing (src/routes/org/activities/posts.tsx & posts.lazy.tsx)

  • Splits files to optimize bundle sizes. Loaders stay in posts.tsx to run immediately on transition, while heavy UI renders in posts.lazy.tsx which is loaded on-demand.

8. Authentication & Route Guards (src/routes/org/activities/meetups/create.tsx, src/routes/login.tsx)

  • Implements route-level bouncers inside the beforeLoad hook.
  • Unauthorized attempts to visit the create page immediately throw a redirect to /login, attaching error alerts via search queries.
  • Maintains login state inside local storage via src/utils/auth.ts.

9. Cache Invalidation (src/routes/org/activities/meetups/create.tsx)

  • Demonstrates calling router.invalidate() to clear stale network caches so the list page automatically displays the newly posted meetup.

⚡ How to Run the Entire App

To run the whole application, you need to start both the mock server and the React app in separate terminal windows.

Step 1: Run the Backend API

cd meetup-mock-api
pnpm install
pnpm start

Step 2: Run the React Tracker Frontend

cd meetup-tracker
pnpm install
pnpm dev

Enjoy learning the best routing mechanism available for the modern web! For more details, refer to the official TanStack Router Documentation.