Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 132 ยท Routing and Apps

Router Types and Router Hooks

Learn the router types (BrowserRouter, HashRouter, MemoryRouter, StaticRouter), the location and history model, the hooks useLocation, useParams, useMatch and useNavigate, and the v5 to v6 mapping.

Every React router tutorial starts with a line like <BrowserRouter> and then moves on, as if the choice did not matter. It does. The router you wrap your app in decides where the current location is stored (the address bar, the hash, or a plain JavaScript array) and what happens when it changes. The hooks inside your components (useLocation, useParams, useNavigate, useMatch) then read from, and write to, that one source of truth.

This lesson explains the four router types, the tiny mental model of location and history that sits under all of them, and each of the main hooks. It ends with a map from the older React Router v5 API (Switch, Redirect, useHistory) to the current one, because you will meet v5 code in the wild. The real library code is shown read-only, since the editor cannot install packages. Every idea also has a runnable stand-in built from the router you wrote in Client-Side Routing; the stand-ins teach the mechanics and are not replacements for the library.

The mental model: location plus history

A router keeps two things.

  • A location: an object describing "where we are": pathname (/users/7), search (?tab=posts), hash (#comments) and state (any value you attached when navigating).
  • A history: a stack of locations with a pointer to the current one. push adds a new entry on top (the back button then goes to the previous one), replace overwrites the current entry, and go(-1) moves the pointer.

Whenever the history changes, the router tells React the location changed, and every component that called useLocation() renders again. Everything else in a router (matching /users/:id, building links, redirecting) is built on those two ideas.

The router types differ in only one respect: which storage backs the history.

Router Backed by URL looks like Typical use
BrowserRouter The History API (pushState) /users/7 Normal websites and apps
HashRouter location.hash /#/users/7 Hosts that cannot rewrite URLs to index.html
MemoryRouter A JavaScript array none (address bar unchanged) Tests, embedded widgets, React Native
StaticRouter A fixed URL string none Server-side rendering of one request

BrowserRouter

BrowserRouter uses history.pushState and listens to popstate, so URLs look clean and a page reload asks the server for exactly that path. This is the default choice, with one condition: the server must answer every unknown path with your index.html, otherwise a reload on /users/7 returns a 404 from the server. Vite's dev server does this for you; on static hosting you configure a "fallback to index.html" rule.

JSX
// main.jsx (read-only: needs react-router)
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Routes, Route } from 'react-router';

createRoot(document.getElementById('root')).render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/users/:userId" element={<User />} />
    </Routes>
  </BrowserRouter>
);

HashRouter

HashRouter keeps the route after a #: https://example.com/app/#/users/7. Browsers never send the part after # to the server, so the server only ever sees /app/. That makes it work on hosts where you cannot configure rewrites (some static file shares, a page opened from file://, embedded in another site). The price is uglier URLs and no real server-side rendering, because the server cannot see the route. You already used this idea in the client-side routing lesson, and it is what the editor on this site needs, because previews run inside a sandbox without the History API.

JSX
// read-only
import { HashRouter } from 'react-router';

createRoot(root).render(
  <HashRouter>
    <App />
  </HashRouter>
);

MemoryRouter

MemoryRouter stores the history in an array inside JavaScript. The address bar never changes. That sounds useless until you need a router without a browser: in unit tests you start the app at a chosen route, in a widget embedded into someone else's page you must not touch the host's URL, and React Native has no address bar at all.

JSX
// A test (read-only)
import { MemoryRouter } from 'react-router';
import { render, screen } from '@testing-library/react';

test('shows the user page', () => {
  render(
    <MemoryRouter initialEntries={['/users/7']}>
      <App />
    </MemoryRouter>
  );
  expect(screen.getByText('User 7')).toBeInTheDocument();
});

StaticRouter

During server-side rendering there is a single request and no navigation. A static router takes the request URL and renders once. In current React Router you use createStaticHandler and StaticRouterProvider from react-router; the older StaticRouter from react-router-dom/server takes a location prop. Both render the same markup the browser router will later take over, which is why the server and the browser must agree on the route table. See SSR and hydration.

JSX
// server.jsx (read-only)
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom/server';

export function render(url) {
  return renderToString(
    <StaticRouter location={url}>
      <App />
    </StaticRouter>
  );
}

One history, three storages (runnable)

Here is the whole idea in about thirty lines. A createMemoryHistory function keeps the stack in an array; swapping it for a function that wrote to window.location.hash would give you a hash router, and one that called pushState would give you a browser router. The components never know which.

A memory history and the location it produces

Notice what push does after you went back: it cuts off the forward entries (entries.slice(0, index + 1)). That is exactly how the browser's back and forward buttons behave, and it is why replace exists: use it when the old entry should not stay in the history, for example after a redirect or a login.

The hooks

A hook can only read the router if a router is above it in the tree; outside a router they throw. All of the hooks below exist with the same names in React Router v6 and v7.

useLocation

useLocation() returns the current location object: pathname, search, hash, state and key. Use it when you need to react to a change of the URL, such as sending a page view to analytics, scrolling to the top on navigation, or reading a message attached through state.

JSX
// read-only
import { useLocation } from 'react-router';

function PageViews() {
  const location = useLocation();
  useEffect(() => {
    analytics.track('page_view', { path: location.pathname + location.search });
  }, [location]);
  return null;
}

useParams

useParams() returns the dynamic segments of the matched route as an object. For path="/users/:userId/posts/:postId" and the URL /users/7/posts/42 it returns { userId: '7', postId: '42' }. Values are always strings: convert with Number(userId) before comparing to a numeric id.

useNavigate

useNavigate() returns a function that changes the location from code, for example after a form succeeds. navigate('/done') pushes, navigate('/done', { replace: true }) replaces, and navigate(-1) goes back. Prefer a <Link> whenever the user clicks something to go somewhere, because links work with middle-click and screen readers; use navigate for results of work (saving, signing in).

JSX
// read-only
const navigate = useNavigate();

async function handleSubmit(e) {
  e.preventDefault();
  await save(form);
  navigate('/orders', { replace: true, state: { saved: true } });
}

useMatch

useMatch(pattern) answers a yes-or-no question about the current URL, independent of the route that rendered the component. It returns a match object (with params and pathname) when the URL fits the pattern and null otherwise. It is the right tool for things like "highlight the Users link while anywhere under /users".

JSX
// read-only
import { useMatch } from 'react-router';

function UsersTab() {
  const match = useMatch('/users/*');
  return <a href="/users" className={match ? 'tab active' : 'tab'}>Users</a>;
}

useMatch reads the URL, whereas useParams reads the route that rendered this component. That is why useParams is empty in a header that sits outside any <Route>, while useMatch('/users/:id') there can still extract the id.

Other hooks worth knowing

  • useSearchParams() reads and writes the query string like useState for ?tab=posts.
  • useOutlet() and Outlet render the child route in a layout.
  • useNavigation() (data routers) tells you whether a navigation or form submission is pending.
  • useHref(to) resolves a relative to into a full href.

The hooks, running on a stand-in router

The next demo wires a memory history to a context and builds useLocation, useNavigate, useParams and useMatch on top. The behavior matches the real hooks for the simple cases shown.

useLocation, useNavigate, useParams and useMatch on a stand-in

Click User 7 and look at the header: useMatch extracts {"userId":"7"} even though the header is not rendered by that route, and Replace with next user changes the entry without adding to the history, so Back skips it.

From React Router v5 to v6 and v7

Older tutorials and codebases use v5. The ideas are the same; the API got smaller and more consistent. Here is the translation table you need to read old code or upgrade it.

v5 v6 and v7 Notes
<Switch> <Routes> Picks the best match by specificity, not the first one in order.
<Route path="/a" component={A} /> <Route path="/a" element={<A />} /> You pass an element, so you can give it props.
exact prop not needed Matching is exact by default; use /a/* for "anything below".
<Redirect to="/b" /> <Navigate to="/b" replace /> Or return a redirect from a loader.
useHistory() useNavigate() history.push(p) becomes navigate(p), history.replace(p) becomes navigate(p, { replace: true }), history.goBack() becomes navigate(-1).
props.match.params useParams() Route components no longer receive match, location or history props.
useRouteMatch() useMatch() Takes a pattern and returns null or a match.
<NavLink activeClassName="on"> <NavLink className={({ isActive }) => ...}> The class (and style) may be a function.
<Prompt> useBlocker() Blocks navigation, for example with unsaved changes.
Nested <Route> inside components Nested <Route> with <Outlet> Relative paths work in nested routes.
react-router-dom package react-router In v7 everything is exported from react-router (v7 still has react-router-dom as a re-export).

When upgrading a large v5 app, React Router publishes a compatibility package, react-router-dom-v5-compat, so you can move route by route instead of all at once.

Common mistakes

  • Using BrowserRouter on a host without an index.html fallback. The home page works, a reload on /users/7 returns 404. Fix the host, or use HashRouter.
  • Reading useParams outside the route that defines the parameter. It returns an empty object; use useMatch with a pattern.
  • Comparing a param to a number. useParams() gives strings, so '7' === 7 is false.
  • Calling navigate() during render. Navigation is a side effect: call it from event handlers and effects, or render <Navigate>.
  • Pushing when you should replace. After a redirect or login, replace keeps the Back button from returning to a page that immediately redirects again.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between the router types?

    Matching, params and hooks work the same everywhere. The router type only decides how the location is stored and updated.
  2. 2. Which router fits a unit test that must start the app at "/users/7"?

    MemoryRouter needs no browser history and lets you choose the starting entries, so tests are isolated and repeatable.
  3. 3. After pressing Back twice you click a new link (push). What happens to the entries that were ahead of you?

    Pushing cuts the history at the current position and adds the new entry, which is how the browser behaves too.
  4. 4. Which v5 code maps to navigate("/home", { replace: true }) in v6 and v7?

    useHistory is replaced by useNavigate, and history.replace becomes navigate with the replace option.
  5. 5. A header rendered outside any Route needs to know whether the URL is under /users. Which hook fits?

    useMatch checks the current URL against a pattern wherever you call it, whereas useParams only sees the route that rendered the component.

Summary

  • A router owns a location and a history stack; hooks read the location and navigate changes it.
  • BrowserRouter uses the History API (needs a server fallback), HashRouter uses #, MemoryRouter keeps entries in an array, StaticRouter renders one URL on the server.
  • useLocation reads the URL, useParams reads the matched route's dynamic segments (as strings), useMatch tests the URL against a pattern, and useNavigate changes it.
  • push cuts off forward entries; replace overwrites the current one.
  • v5 to v6/v7: Switch to Routes, component to element, Redirect to Navigate, useHistory to useNavigate, useRouteMatch to useMatch.

Next: App Architecture