Uncaught Error: UseNavigate() Used Only In The Context Of A <Router>

usenavigate() may be used only in the context of a component error solution.

Hook may be used only in the context error is quite common. This can happen when you try to use context which is not in scope.

For Ex: your library is providing context api feature. To use it you need to wrap other component inside your main context provider component. If you do not do that it will result in error: Hook may be used only in the context. Because child hook do not have parent which can give it proper context.

Code with error:

import { Route, BrowserRouter as Router, Routes } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/contact" element={<ContactPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
    </Router>
  )
}

From above conde snippet you can see that App component is try to use useNavigate hook. Now App it self is top level component and do not wrapped insided . So, context of the Router will not available to it.

We need to re-structre this app in a way that it can have <Router> as top level. Now <Router> can pass its conetxt to child elements.

Code with error solution:

import { Route, BrowserRouter as Router, Routes } from "react-router-dom";

function App() {
  return (
    <Router>
      <AppRoutes/>
    </Router>
  )
}

function AppRoutes() {
  let navigate = useNavigate();

  return (
      <Routes>
        <Route path="/" element={<HomePage />} />
        <Route path="/contact" element={<ContactPage />} />
        <Route path="*" element={<NotFoundPage />} />
      </Routes>
  )
}

From above codne snippet you can see that we are wrapping our <AppRoutes /> component inside <Router>. Now, inside of <AppRoutes /> component we can use useNavigate hook. now useNavigate hook can get its context from its parent <Router> component.

In most cases you need to re-structure your component layout to solve this issue.

Related Articles

js interview questions