Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 50 ยท Practice and Review

Migrating From v5, v6 and Remix

Upgrade an existing app to React Router 7: replace Switch and useHistory, move from v6 with future flags to v7, and port a Remix app to framework mode, step by step.

Most React Router code in the wild is not v7. You will meet apps that still use Switch and useHistory (v5), apps on v6 with BrowserRouter and Routes, and Remix applications that are now React Router in disguise. Each needs a different amount of work, and the good news is that the three jumps are not equally scary: v6 to v7 is small, v5 to v6 is a rewrite of how routes are declared, and Remix to React Router is mostly renaming plus configuration.

This lesson is a map for all three jumps. The code in the "Before" and "After" blocks is real React Router code and read-only, because the live editor cannot install packages. Three runnable demos show the parts that are easiest to get wrong: how matching changed, how history calls map to navigate, and what a small automated rewrite looks like. Background: What Is React Router? explains the history of the versions, and Choosing Between Declarative, Data and Framework Mode explains the modes you can land in.

Always check the official upgrade guide of the exact version you target before you start. Version numbers, flag names and codemods change, and this lesson can only describe the shape of the migration. Run the app's tests (or click through it) after every step, and commit after each one so you can bisect problems.

Pick your path

flowchart LR
    A["React Router v5<br/>Switch, useHistory"] --> B["v6<br/>Routes, useNavigate"]
    B --> C["v6 with future flags on"]
    C --> D["v7 declarative or data mode"]
    D --> E["v7 framework mode"]
    F["Remix v2<br/>(Vite)"] --> G["Remix v2 with future flags on"]
    G --> E

Go through every box on your route, in order. Skipping a step usually turns one small problem into a pile of them.

If you start on v5, finish the move to v6 first, and only then upgrade to v7. Do not try to jump straight from v5 to v7.

From v5 to v6

The big changes are about how routes are described and how paths are resolved.

v5 v6 and v7
<Switch> <Routes>
<Route path="/a" component={A} /> or render={...} <Route path="/a" element={<A />} />
exact gone, every route matches the whole path by default
<Redirect from="/old" to="/new" /> <Route path="/old" element={<Navigate to="/new" replace />} />
useHistory() and history.push useNavigate() and navigate(to)
useRouteMatch() useMatch(pattern)
withRouter removed, use the hooks
<NavLink activeClassName="on" exact> <NavLink end className={({ isActive }) => ...}>
<Prompt> useBlocker (needs a data router)
Routes declared inside components Nested <Route> children and <Outlet>
path with regular expressions removed

A typical v5 file and its v6 version:

JSX
// Before: React Router v5 (read-only)
import { BrowserRouter, Switch, Route, Redirect, Link } from 'react-router-dom';

export default function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link> <Link to="/users">Users</Link></nav>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/users" component={Users} />
        <Route path="/users/:id" component={UserPage} />
        <Redirect from="/people" to="/users" />
      </Switch>
    </BrowserRouter>
  );
}
JSX
// After: React Router v6/v7 (read-only)
import { BrowserRouter, Routes, Route, Navigate, Link } from 'react-router';

export default function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link> <Link to="/users">Users</Link></nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/users" element={<Users />} />
        <Route path="/users/:id" element={<UserPage />} />
        <Route path="/people" element={<Navigate to="/users" replace />} />
      </Routes>
    </BrowserRouter>
  );
}

Two details here are classic traps. First, <Redirect> replaced the history entry, but <Navigate> pushes one unless you add replace; without it the Back button bounces the user straight back to the old URL, which redirects again. Second, element takes an element (<Home />), not a component (Home), so props can be passed directly and the router does not need to know how to create your component.

Matching changed: from "first match" to "best match"

In v5 the Switch walked its children in order and rendered the first one whose path matched, and without exact a path matched any URL that started with it. That is why every v5 app has exact on its home route, and why the order of routes mattered. v6 scores the routes instead and picks the most specific full match, so exact disappears and /users/new beats /users/:id wherever you wrote it (see Routes and Matching).

The demo applies both rules to the same list of routes. Look at the three columns for each URL.

Switch (first match) versus v6 (best match)

The v6 column is the same for every ordering of the list. The v5 columns are not: reorder paths in the code and watch the other two columns change.

useHistory becomes useNavigate

useHistory() returned a mutable history object with push, replace, goBack and friends. useNavigate() returns one function. The mapping is mechanical:

v5 v6 and v7
history.push('/a') navigate('/a')
history.push('/a', { from: 'x' }) navigate('/a', { state: { from: 'x' } })
history.replace('/a') navigate('/a', { replace: true })
history.goBack() navigate(-1)
history.goForward() navigate(1)
history.go(-2) navigate(-2)

The demo runs the same scenario through a simulated history stack, once with v5-style calls and once with the v6 calls, and shows that the result is identical. It is a toy (the real thing is the browser's History API, explained in How Routing Works Under the Hood), but it makes the push/replace/back semantics concrete.

history calls and navigate calls give the same stack

Look at the last row: after goBack the user stands on /products, and pushing /cart discards the forward entries (/products/8). That is how browsers behave and what both APIs do.

Nested routes and relative paths

The largest change is structural. In v5 a component such as Users could contain its own <Switch> with routes built from match.path. In v6 you declare the nesting in the route tree and let the parent render an <Outlet />; child paths are relative to the parent:

JSX
// After: v6/v7 nested routes (read-only)
<Routes>
  <Route path="users" element={<UsersLayout />}>
    <Route index element={<UserList />} />
    <Route path=":id" element={<UserPage />} />
    <Route path=":id/edit" element={<EditUser />} />
  </Route>
</Routes>

If a component still renders its own <Routes> for a section, the parent route needs a trailing splat so that the parent keeps matching deeper URLs: <Route path="users/*" element={<UsersSection />} />. Links also changed: a to without a leading slash is resolved against the route, not the full URL, which is usually what you wanted (see Relative Links and Relative Routing). Optional segments came back in 6.5 (path="users/:id?"), but regular expressions in paths did not.

A tiny automated rewrite

Most of the table above is mechanical, so teams automate it. A real migration uses codemods that understand the syntax tree, because text replacement breaks on formatting, comments and unusual code. The demo below is a toy that applies a handful of regular expressions to the v5 sample. Edit the input to see what it handles and, more importantly, what it silently leaves alone.

A toy v5 to v6 rewriter

The sample converts completely: the import line, the history calls, component to element, exact and Redirect. Now break it. Add <Route path="/x" render={() => <X />} />, a path such as /user/:id(\d+), or a withRouter(Checkout) call, and the toy passes all three through untouched, even though none of them works in v6. It also cannot notice that a relative to now resolves against the route instead of the full URL. A rewriter saves hours on the boring 90 percent, but the compiler and your tests have to find the rest.

From v6 to v7

The jump from 6.x to 7 is deliberately small. The React Router team published v7 as the next major version of v6, and the work was moved into a set of future flags in the 6.x releases. The recipe:

  1. Update to the latest 6.x release first. Fix the deprecation warnings and any test failures.
  2. Turn on the future flags one by one, in the order of the upgrade guide, and fix what each one changes. The flags are opt-in behavior changes of v7 shipped early:
JSX
// v6 with future flags (read-only)
import { BrowserRouter, createBrowserRouter, RouterProvider } from 'react-router-dom';

// declarative mode
<BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
  <App />
</BrowserRouter>;

// data mode
const router = createBrowserRouter(routes, {
  future: {
    v7_relativeSplatPath: true,
    v7_fetcherPersist: true,
    v7_normalizeFormMethod: true,
    v7_partialHydration: true,
    v7_skipActionErrorRevalidation: true,
  },
});
<RouterProvider router={router} future={{ v7_startTransition: true }} />;
  1. Bump the packages: install react-router 7 and remove react-router-dom. The new package contains everything. Then change imports from 'react-router-dom' to 'react-router' (a plain search and replace; react-router-dom still exists as a re-export for compatibility, but new code should not use it). One import is special: the DOM RouterProvider for data mode now comes from 'react-router/dom'.
  2. Replace the removed helpers: json() and defer() are gone. A loader can return a plain object, and returning promises inside that object is how you stream (see Streaming Data with Await and Suspense). Use data(value, { status }) when you need to set a status or headers.
  3. Check your runtime: v7 needs a currently supported Node and React 18 or newer.
JSX
// v7 imports (read-only)
import { createBrowserRouter, Link, Outlet, data } from 'react-router';
import { RouterProvider } from 'react-router/dom';

What do the flags actually change? Most of them are small corrections: how .. behaves inside splat routes, wrapping state updates in React.startTransition, keeping a fetcher alive until it is idle, upper-casing formMethod, and not re-running loaders after an action that failed. Each is described in the 6.x release notes. Turning them on before the major upgrade means a bug has one obvious cause.

From Remix to React Router framework mode

Remix v2 on Vite and React Router 7 in framework mode are the same product at two version numbers: React Router v7 is the next Remix. So a Remix app does not need a rewrite, but it does need a methodical port. The usual order:

  1. Upgrade to the latest Remix v2 and enable all its future flags (the ones that match v7 behavior: single fetch, relative splat paths, lazy route discovery, and the route config flag). Make sure the app uses the Vite plugin; the old compiler has no upgrade path.
  2. Move to the new packages and imports:
Terminal
# read-only: package names change, commands are examples
npm uninstall @remix-run/react @remix-run/node @remix-run/serve @remix-run/dev
npm install react-router @react-router/node @react-router/serve
npm install -D @react-router/dev
  1. Change the Vite plugin and add the config file:
TypeScript
// vite.config.ts (read-only)
import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [reactRouter()], // was: remix()
});
TypeScript
// react-router.config.ts (read-only)
import type { Config } from '@react-router/dev/config';

export default { ssr: true } satisfies Config;
  1. Add app/routes.ts. Remix discovered routes from file names automatically; React Router wants an explicit route config. If you want to keep your file-name convention, an adapter does it for you:
TypeScript
// app/routes.ts (read-only)
import { type RouteConfig } from '@react-router/dev/routes';
import { flatRoutes } from '@react-router/fs-routes';

export default flatRoutes() satisfies RouteConfig;
  1. Update the two entry files: RemixBrowser becomes HydratedRouter (from react-router/dom) and RemixServer becomes ServerRouter.
  2. Replace json() and defer() in loaders and actions with plain returns or data(), and update your type imports (LoaderFunctionArgs and friends become the generated Route.LoaderArgs types, see Route Config and File Routes).

The meta, links and headers exports, loader/action and clientLoader carry over almost unchanged. The Remix team also published a codemod for the import renames; check the current upgrade guide for its exact name, run it on a clean git tree, and review the diff like any other change.

A migration checklist

  • Get the tests green and commit before you start.
  • One jump at a time: v5 to v6, then 6.x with flags, then v7, then (optionally) a different mode.
  • After each step, run the type check and click through navigation, redirects, back and forward, deep links and error pages.
  • Search the code for the old names: Switch, Redirect, useHistory, withRouter, component=, activeClassName, json(, defer(, @remix-run.
  • Fix the behavior differences by hand: redirects that must be replace, links that were absolute and now are relative, and routes whose order used to matter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In v5, why did almost every home route carry the exact prop?

    v5 used prefix matching and rendered the first matching route in a Switch. Every URL starts with '/', so without exact the home page would always win.
  2. 2. Which line is the correct v6 replacement for <Redirect from='/old' to='/new' />?

    Redirects are now a Navigate element inside a route. Add replace, because Navigate pushes a history entry by default, while Redirect replaced it.
  3. 3. What is the v6 equivalent of history.goBack()?

    navigate accepts a number as a delta in the history stack. -1 goes back one entry and 1 goes forward.
  4. 4. What is the recommended way to prepare for the v6 to v7 upgrade?

    The future flags ship v7 behavior early, so each behavior change can be fixed on its own, while the app still runs on a version you know.
  5. 5. A Remix v2 app moves to React Router framework mode. What is the relationship between the two?

    React Router v7 merged Remix's features into the router. A port renames packages and imports, adds an explicit routes file and the new Vite plugin, and replaces json() and defer().

Summary

  • v5 to v6 changes how routes are declared (Routes, element, nested Route plus Outlet) and how they match (best match instead of first match, no exact).
  • Map useHistory calls mechanically to useNavigate: push is navigate(to), replace is navigate(to, { replace: true }), goBack is navigate(-1). Navigate needs replace to behave like Redirect.
  • v6 to v7 is small if you upgrade to the latest 6.x first and enable the future flags one at a time. Then swap react-router-dom for react-router, import the DOM RouterProvider from react-router/dom and replace json() and defer().
  • A Remix app moves to framework mode by renaming packages, switching the Vite plugin, adding react-router.config.ts and app/routes.ts, and updating entry files.
  • Automate the mechanical parts with a real codemod, but test after every step, because renames cannot find behavior changes.

Next: Common Mistakes and Debugging