useLocation returns undefined

All we need is an easy explanation of the problem, so here it is.

I use useLocation hook in my app from react-router-dom v5. However, it always returns me undefined. Here is the minimal setup to reproduce this issue.

App.js

import { Route, NavLink as Link, Switch, useLocation } from "react-router-dom";

export default function App() {
  const { location } = useLocation();
  console.log(location);
  return (
    <div>
      <div
        style={{
          display: "flex",
          backgroundColor: "cadetblue",
          alignItems: "center",
          columnGap: "10px"
        }}
      >
        <h1>Menu</h1>
        <Link to="/invoices">Go to invoices</Link>
        <Link to="/eshop">Go to eshop</Link>
      </div>

      <Switch>
        <Route path="/invoices">
          <h2>Invoices</h2>
        </Route>
        <Route path="/eshop">
          <h2>Eshop page</h2>
        </Route>
      </Switch>
    </div>
  );
}

index.js

import { createRoot } from "react-dom/client";
import { MemoryRouter as Router } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <Router>
    <App />
  </Router>
);

code sandbox: https://codesandbox.io/s/hungry-cloud-i2hui2?file=/src/App.js

Any ideas?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should modify your { location } to location

import { Route, NavLink as Link, Switch, useLocation } from "react-router-dom";

export default function App() {
  const location = useLocation(); //removed brackets
  console.log(location);
  return (
    <div>
      <div
        style={{
          display: "flex",
          backgroundColor: "cadetblue",
          alignItems: "center",
          columnGap: "10px"
        }}
      >
        <h1>Menu</h1>
        <Link to="/invoices">Go to invoices</Link>
        <Link to="/eshop">Go to eshop</Link>
      </div>

      <Switch>
        <Route path="/invoices">
          <h2>Invoices</h2>
        </Route>
        <Route path="/eshop">
          <h2>Eshop page</h2>
        </Route>
      </Switch>
    </div>
  );
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply