createMemoryRouter
Create a new data router that manages the application path using an in-memoryHistory stack. Useful for non-browser environments without a DOM API, such as testing or React Native.
Function Signature
Route Configuration
Theroutes parameter accepts the same RouteObject[] configuration as createBrowserRouter. See the createBrowserRouter route configuration for complete details.
Options Parameter
Initial Entries
TheinitialEntries option allows you to specify the starting history stack:
- A string path:
"/home","/products/123","/search?q=test" - A partial Location object:
Return Type
Returns an initializedDataRouter 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
UsecreateMemoryRouter 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
- Isolation: Tests don’t interfere with each other via shared browser history
- Speed: No browser navigation overhead
- Determinism: Start each test with a known history state
- Flexibility: Test specific history scenarios easily
Differences from Other Routers
| Feature | createMemoryRouter | createBrowserRouter | createHashRouter |
|---|---|---|---|
| URL Updates | ✗ No | ✓ Yes | ✓ Yes (hash) |
| Browser History | ✗ No | ✓ Yes | ✓ Yes |
| Server Config | Not needed | Required | Not needed |
| Testing | ✓ Perfect | ✗ Not ideal | ✗ Not ideal |
| Production Use | ✗ Rare | ✓ Recommended | ✓ Fallback |
| React Native | ✓ Yes | ✗ No | ✗ No |
Common Testing Patterns
Setup Helper
Custom Render Helper
Related
<RouterProvider>- Component to render the routercreateBrowserRouter- Browser history-based routingcreateHashRouter- Hash-based routing<MemoryRouter>- Declarative version for simple use cases