React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)
What is the difference between BrowserRouter, HashRouter, and MemoryRouter?
All three are drop-in <Router> implementations from react-router-dom (see What are the <Router> components of React Router v6?) that wrap a different history implementation, so your app's routes work the same way — only how the URL is stored/read differs.
| Aspect | <BrowserRouter> | <HashRouter> | <MemoryRouter> |
|---|---|---|---|
| URL format | Clean URLs using the HTML5 History API (/about) | Uses a URL hash fragment (/#/about) | No URL at all — history is kept purely in memory |
| Where history lives | Browser's window.history | Browser's window.location.hash | An in-memory array/stack, not tied to the browser |
| Server requirement | Server must be configured to return index.html for every route (fallback routing), otherwise a hard refresh on /about 404s | None — the part after # is never sent to the server, so any static server works with zero config | Not applicable — there's no browser/server involved |
| Typical use case | Standard web apps deployed behind a server/CDN you control (or configure) for SPA fallback | Static hosting with no server-side routing support (e.g., plain GitHub Pages, legacy browsers) | Unit/integration tests, Storybook, React Native, or any non-DOM environment |
| Back/forward buttons | Fully supported via native browser history | Supported, but the hash shows up in the URL/bookmark | Not applicable — no visible URL to bookmark/share |
| Bookmarking/sharing links | Works naturally | Works, but URLs look less clean (example.com/#/about) | N/A — not meant to be visible to a user |
jsx
import { BrowserRouter } from "react-router-dom";
// Standard choice for most deployed web apps
<BrowserRouter>
<App />
</BrowserRouter>;
jsx
import { HashRouter } from "react-router-dom";
// Good when you can't configure server-side rewrites
<HashRouter>
<App />
</HashRouter>;
jsx
import { MemoryRouter } from "react-router-dom";
// Great for tests — you can even seed the starting route
render(
<MemoryRouter initialEntries={["/dashboard"]}>
<App />
</MemoryRouter>
);
In short: use BrowserRouter for real, deployed apps with clean URLs (as long as your server supports SPA fallback), HashRouter when you can't control server routing (plain static hosting), and MemoryRouter for tests or non-browser environments where there's no real URL bar to sync with.