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.

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.
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
createRootoutside 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-dominnode_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.
// 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:
// 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 />);// 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>;
}// 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:
| Message | Hook | Missing provider |
|---|---|---|
useNavigate() may be used only in the context of a <Router> | useNavigate | any router |
useLocation() may be used only in the context of a <Router> | useLocation | any router |
useRoutes() may be used only in the context of a <Router> | useRoutes | any router |
useParams must be used within a Route | useParams | router plus matching route |
Cannot destructure property 'basename' of useContext(...) as it is null | internal | any router |
Key Comparison Table
| Router component | URL source | Typical use |
|---|---|---|
BrowserRouter | History API | normal single-page app |
HashRouter | location.hash | static file hosting with no rewrite rules |
MemoryRouter | in-memory stack | unit tests and Storybook |
createBrowserRouter + RouterProvider | History API, data APIs | loaders, actions, error elements |
StaticRouter | supplied location | server-side rendering |
Both styles provide the same context, but the data router changes which hooks are legal:
| Need | BrowserRouter | createBrowserRouter |
|---|---|---|
useNavigate | yes | yes, also available in loaders via argument |
useLoaderData | no | yes |
| Error handling per route | errorElement on a route object | same, plus errorElement on the root |
| Nested layouts | <Routes> children | route objects with children |
| Testing | wrap in MemoryRouter | wrap in RouterProvider with a memory router |
Diagnosis order:
| Symptom | Likely cause | Check |
|---|---|---|
| Every component throws | provider missing from main | render tree in main.tsx |
| One feature throws | that feature renders a separate root or portal | createRoot, createPortal calls |
| Only tests throw | no wrapper in render | test setup file |
| Works locally, fails in build | two package copies bundled | npm 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.
// 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 hereFix 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.
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.
// router.ts
import { createBrowserRouter } from "react-router-dom";
export const router = createBrowserRouter(routes);// 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.
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.
// 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 documentationThe React documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact 19: Support for defaultProps will be removed
React 19 ignores defaultProps on function components, so a default becomes undefined. Move defaults into the parameter list and handle null honestly.
React: Each child in a list should have a unique key prop
Keys tell React which item is which between renders. Use stable ids, avoid index keys and put the key on the mapped element, not on a wrapper.
react-hook-form with zod 4: resolver type errors after the upgrade
Zod 4 split input from output and resolvers v5 re-typed Resolver. Drop the generic, or pass all three, and the errors disappear.
React Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
More in React
All React guidesThe guides filed next to this one in React, in library order.