Chapter 16: Route Trees
Core Idea
TanStack Router matches URLs against a nested route tree that maps directly to a nested component tree; the tree can be built via file-based routing (recommended) or code-based routing, both offering identical core functionality.
Key Concepts
- Route Tree: A hierarchical structure of routes where nesting in the tree produces nesting in the rendered component tree (e.g.
blog/posts/$postId renders <Blog><Posts><Post/></Posts></Blog>).
- File-Based Routing: The preferred method; routes are declared as files/folders under
/routes, requiring less code for equivalent or better results than code-based routing.
- Code-Based Routing: An alternative, fully-in-code way to construct the same route tree (see Ch 20).
- Root file (
__root.tsx): The top of the route tree, from which all other route files descend.
- Tree Configuration Styles: Flat routes (dot notation filenames), Directory routes (nested folders), Mixed flat+directory routes, Virtual File Routes (programmatic mapping to real files), and Code-Based Routes.
Key Takeaways
- File-based routing and code-based routing produce the same underlying route tree structure and support identical features; file-based is recommended for less boilerplate.
- Nesting in the file/route tree directly determines component nesting at render time.
- Multiple file-organization styles (flat, directory, mixed, virtual) can be combined freely within one project.
Connects To
- Ch 15: Routing Concepts, defines the building blocks (dynamic segments, layouts, etc.) used within a route tree.
- Ch 18: File-Based Routing, the detailed flat/directory/mixed configuration reference.
- Ch 19: Virtual File Routes, an alternative tree-building method referenced here.
- Ch 20: Code-Based Routing, the non-file-based alternative.