Capítulo 31 de 57

Chapter 31: History Types

Core Idea

TanStack Router relies on a history abstraction from @tanstack/history; a browser history instance is created automatically by default, but you can supply createBrowserHistory, createHashHistory, or createMemoryHistory explicitly to createRouter({ history }) for different environments.

Key Concepts

  • createBrowserHistory: The default; uses the browser's native History API (pushState/popState) to manage navigation.
  • createHashHistory: Tracks routes via the URL hash (#/path) instead of the path itself; useful when the server can't be configured to rewrite all requests to index.html, or in environments without a configurable server.
  • createMemoryHistory({ initialEntries }): Keeps history entirely in memory rather than touching the URL/browser; useful for non-browser environments, testing, or when components shouldn't interact with the real URL. initialEntries seeds the starting stack (e.g. ['/']).
  • Passing a Custom History: Any of these instances is passed via createRouter({ routeTree, history: customHistory }).

Code Examples

import { createMemoryHistory, createRouter } from '@tanstack/react-router'

const memoryHistory = createMemoryHistory({
  initialEntries: ['/'], // Pass your initial url
})

const router = createRouter({ routeTree, history: memoryHistory })
  • What it demonstrates: Creating a router backed by in-memory history instead of the browser's real URL, useful for tests or non-browser hosts.

Key Takeaways

  1. Default browser history is right for standard SPAs; reach for hash history only when server rewrites to index.html aren't possible, and memory history for tests, SSR bootstrapping, or embedded/non-browser environments.
  2. The history instance is a pluggable dependency injected at createRouter() time, not hardcoded, so the same route tree can run under different history backends without route code changes.
  3. For server-side rendering, see the SSR guide's "Automatic Server History" for how history is handled on the server specifically (not detailed in this chapter).

Connects To

  • Ch 23: Navigation, whose NavigateOptions.replace interacts with whichever history instance is active.
  • Ch 32: Scroll Restoration, which keys scroll positions off history entry state.