← flaviocopes.com

React Router, why useLocation and useHistory might return undefined

Published Feb 08 2021

I was having some head scratching moment when using the useLocation and useHistory hooks with React Router.

const history = useHistory()
const location = useLocation()

They both returned undefined.

Turns out I was adding the Router to the DOM with <Router>...</Router> in the same component I was using useLocation and useHistory.

Then I found this issue that explained I could not do that.

I had to move the <Router>...</Router> wrapping of my component one level up. In my case, I did that in the index.js file:

import { BrowserRouter as Router } from 'react-router-dom'



        <App />

Wanna go from noobie to expert?

I wrote an entire book on this topic 👇

© 2023 Flavio Copes Flavio Copes using Notion to Site Notion to Site. Follow on Twitter

Solopreneur? Wannabe? Adventure awaits