Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React: useNavigate() may be used only in the context of a Router

The hook throws because no Router sits above it. Move the call inside a route tree, fix duplicate router packages, and keep navigation out of render.

~5 min readReact
#react#react-router#usenavigate#routing
Bold white headline reading NO ROUTER with a React component crate floating above a missing cyan router gate.

Introduction & Quick Summary

Calling the navigation hook outside a router throws immediately:

Error: useNavigate() may be used only in the context of a <Router> component.
code
at useNavigate (react-router/dist/index.js:1234:13) at LoginForm (src/features/auth/LoginForm.tsx:18:20) at renderWithHooks (react-dom.development.js:16305:18)

React Router provides its context through a <Router> component. Any component that calls useNavigate, useLocation, useParams, useSearchParams, or useMatches must render somewhere below one. The hook throws when the context value is null, which happens in three situations: no router at all, a router in a sibling tree, or a router from a different copy of the package.

Where it appears:

  • A component rendered by createRoot outside the element tree that holds <BrowserRouter>.
  • A test that renders the component alone, without a router wrapper.
  • A modal, toast, or error boundary mounted at the document root, separate from the app tree.
  • Two copies of react-router-dom in node_modules, so the component reads one context and the provider writes another.
  • A component imported from a library that bundles its own router version.

Quick answer: wrap the tree that renders the component, keep one router version in the dependency graph, and call the hook only inside components that render under that provider.

Core Mechanics, Signatures & Reproducible Setup

useNavigate reads a context object and returns a stable function. When the context is null, it throws rather than returning a no-op, because navigating nowhere is always a bug.

ts
// simplified shape of what the hook does const NavigateContext = createContext<NavigateFunction | null>(null); export function useNavigate(): NavigateFunction { const navigate = useContext(NavigateContext); if (navigate === null) { throw new Error("useNavigate() may be used only in the context of a <Router> component."); } return navigate; }

The message names <Router> because every router component, BrowserRouter, HashRouter, MemoryRouter, and the data routers, renders the same internal Router and provides that value.

A complete reproduction in about twenty lines:

tsx
// main.tsx -- the bug: provider is not above the consumer import { createRoot } from "react-dom/client"; import { BrowserRouter } from "react-router-dom"; import { LoginForm } from "./LoginForm"; createRoot(document.getElementById("root")!).render(<LoginForm />);
tsx
// LoginForm.tsx import { useNavigate } from "react-router-dom"; export function LoginForm() { const navigate = useNavigate(); // throws: no <Router> above this element return <button onClick={() => navigate("/dashboard")}>Sign in</button>; }
tsx
// main.tsx -- the fix createRoot(document.getElementById("root")!).render( <BrowserRouter> <LoginForm /> </BrowserRouter> );

The same context rule produces a family of errors with different hook names:

MessageHookMissing provider
useNavigate() may be used only in the context of a <Router>useNavigateany router
useLocation() may be used only in the context of a <Router>useLocationany router
useRoutes() may be used only in the context of a <Router>useRoutesany router
useParams must be used within a RouteuseParamsrouter plus matching route
Cannot destructure property 'basename' of useContext(...) as it is nullinternalany router

Key Comparison Table

Router componentURL sourceTypical use
BrowserRouterHistory APInormal single-page app
HashRouterlocation.hashstatic file hosting with no rewrite rules
MemoryRouterin-memory stackunit tests and Storybook
createBrowserRouter + RouterProviderHistory API, data APIsloaders, actions, error elements
StaticRoutersupplied locationserver-side rendering

Both styles provide the same context, but the data router changes which hooks are legal:

NeedBrowserRoutercreateBrowserRouter
useNavigateyesyes, also available in loaders via argument
useLoaderDatanoyes
Error handling per routeerrorElement on a route objectsame, plus errorElement on the root
Nested layouts<Routes> childrenroute objects with children
Testingwrap in MemoryRouterwrap in RouterProvider with a memory router

Diagnosis order:

SymptomLikely causeCheck
Every component throwsprovider missing from mainrender tree in main.tsx
One feature throwsthat feature renders a separate root or portalcreateRoot, createPortal calls
Only tests throwno wrapper in rendertest setup file
Works locally, fails in buildtwo package copies bundlednpm ls react-router-dom

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Put the provider above every consumer, including portals

Portals keep the React tree for context but move DOM position, so a modal rendered through a portal still sees the router. A modal rendered through a second createRoot does not.

tsx
// works: portal keeps context return createPortal(<Modal />, document.body); // fails: new root, new tree const host = document.getElementById("modal-root")!; createRoot(host).render(<Modal />); // useNavigate throws here

Fix the second case by rendering the portal from inside the app tree, or by passing navigate into the separate root as a prop.

2. Remove duplicate router packages

Two installed copies create two contexts with the same shape. The provider writes to one, the hook reads the other, and nothing in the error points at the dependency graph.

bash
npm ls react-router-dom react-router # example output showing the problem # app@1.0.0 # ├── react-router-dom@7.9.1 # └─┬ some-ui-kit@2.1.0 # └── react-router-dom@6.30.0
{ "overrides": { "react-router-dom": "7.9.1" } }

Add the override, delete node_modules and the lockfile entry, reinstall, and confirm with npm ls that only one version remains. Paste package.json into JSON to check it is valid after hand-editing.

3. Navigate from outside a component

HTTP interceptors, store actions, and WebSocket handlers have no component and cannot call the hook. Export the router instance, or queue the navigation to the app.

tsx
// router.ts import { createBrowserRouter } from "react-router-dom"; export const router = createBrowserRouter(routes);
ts
// api.ts import { router } from "./router"; export function handleUnauthorized() { localStorage.removeItem("token"); router.navigate("/login", { replace: true }); }

With BrowserRouter instead of a data router, keep a ref set by a component inside the tree and call the ref. Never import a hook and call it at module scope.

4. Give tests a router

Testing Library renders a component in isolation, so any test of a component that navigates needs a router wrapper.

tsx
import { render, screen } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; function renderWithRouter(ui: React.ReactElement, { route = "/" } = {}) { return render(<MemoryRouter initialEntries={[route]}>{ui}</MemoryRouter>); } test("redirects after sign in", async () => { renderWithRouter(<LoginForm />, { route: "/login" }); // assertions });

Put the helper in a shared test utility so new tests cannot forget it. Update the file paths of moved helpers with Diff instead of retyping import blocks.

5. Do not mix Next.js navigation with React Router

In a Next.js app the equivalent hook comes from next/navigation and needs no provider. Importing react-router-dom there produces this same error and a larger bundle.

tsx
// Next.js: correct import { useRouter } from "next/navigation"; export function LoginForm() { const router = useRouter(); return <button onClick={() => router.push("/dashboard")}>Sign in</button>; }

Two packages that both export useNavigate or Router are the usual source of a wrong import, so check the import path in the throwing file before changing the provider.

Common Compilation/Runtime Mistakes & Version Gotchas

Calling navigate during render. The hook throws only outside a router, but calling the returned function in the render body triggers a state update during render and a warning or loop. Move it into an event handler or an effect with a guard.

Missing effect dependencies. An effect that navigates on a condition and omits the values it reads either never runs again or runs on every render. List the dependencies and bail out early when already on the target path.

Hooks in class components. useNavigate cannot be used in a class component at all. Wrap the class in a function component, or use the navigate prop pattern that React Router v5 offered through withRouter before it was removed.

Package rename across majors. React Router v7 publishes the DOM bindings from react-router, and v6 published them from react-router-dom. Importing from the wrong package can pull a second copy and split the context. Check the major version in package.json and match the import path to it.

Breaking changes to watch. In v6.4 and later, data routers changed which props RouterProvider accepts, and v7 removed the element cloning behaviour of v5. An app partially migrated to route objects often has two routers in the tree, one inside the other, which hides the real error until a component outside both calls the hook.

Verifying the fix. The error must disappear for every route, not only the one you tested: grep the source for the hook names with Regex to list every call site, then open each route in the browser and confirm navigation still changes the URL without a full reload.

Reference material: useNavigate and Routing.

Official references

primary documentation

The React documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.