What is MemoryRouter in React?

This article provides a comprehensive overview of MemoryRouter in React Router, explaining its core functionality, key use cases, and how it differs from traditional routing solutions. You will learn why this specialized router is essential for testing components, how it operates in non-browser environments like React Native, and how to implement it in your code.

Understanding MemoryRouter

In standard web applications, React Router uses BrowserRouter to sync the application’s UI with the browser’s address bar. This relies on the HTML5 history API to read and write URLs.

MemoryRouter, on the other hand, stores its history entirely in memory. It does not read from or write to the browser’s address bar. Instead, it keeps track of the navigation history stack internally in a simple JavaScript array. Because it does not rely on a browser window, it is highly versatile and can run in any JavaScript environment.

Key Use Cases for MemoryRouter

Because MemoryRouter operates independently of the browser’s URL, it is the ideal choice for several specific scenarios:

How to Implement MemoryRouter

Implementing MemoryRouter is straightforward. It accepts many of the same children as other routers, but it also includes unique properties to help you mock navigation states.

Here is a basic implementation example:

import { MemoryRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

function App() {
  return (
    <MemoryRouter initialEntries={['/home', '/about']} initialIndex={1}>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </MemoryRouter>
  );
}

Key Props of MemoryRouter

MemoryRouter vs. BrowserRouter

While both components manage routing, they serve different purposes:

Feature BrowserRouter MemoryRouter
History Source HTML5 History API (Browser URL) JavaScript Memory (Array)
URL Visibility Visible and changeable by user Invisible and simulated
Primary Use Case Production web applications Testing, mobile apps, Storybook
Environment Browser only Any JavaScript environment