Skip to main content

createMemoryRouter

Create a new data router that manages the application path using an in-memory History stack. Useful for non-browser environments without a DOM API, such as testing or React Native.

Function Signature

Route Configuration

The routes parameter accepts the same RouteObject[] configuration as createBrowserRouter. See the createBrowserRouter route configuration for complete details.

Options Parameter

Initial Entries

The initialEntries option allows you to specify the starting history stack:
Each entry can be:
  • A string path: "/home", "/products/123", "/search?q=test"
  • A partial Location object:

Return Type

Returns an initialized DataRouter instance to be passed to <RouterProvider>.

Examples

Basic Usage

With Initial Entries

Testing with History Stack

Testing Loaders

Testing Error Boundaries

Testing Actions

With Complex Initial State

Integration Test Example

React Native Example

Use Cases

When to Use createMemoryRouter

Use createMemoryRouter when:
  • Testing: Unit or integration testing React Router applications
  • React Native: Building mobile apps with React Native
  • Electron: Desktop applications without browser history
  • Node.js: Server-side rendering or other Node environments
  • Storybook: Documenting components that use routing
  • Isolated environments: Any non-browser environment needing routing

Advantages

  • No URL side effects: Perfect for testing since it doesn’t modify the browser URL
  • Full control: Complete control over the history stack via initialEntries
  • Deterministic: Predictable behavior for testing
  • Platform agnostic: Works in any JavaScript environment
  • All data router features: Full support for loaders, actions, and other data APIs

Testing Benefits

  1. Isolation: Tests don’t interfere with each other via shared browser history
  2. Speed: No browser navigation overhead
  3. Determinism: Start each test with a known history state
  4. Flexibility: Test specific history scenarios easily

Differences from Other Routers

Common Testing Patterns

Setup Helper

Custom Render Helper