Skip to content

React Router, why useLocation and useHistory might return undefined

New Course Coming Soon:

Get Really Good at Git

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'

...

ReactDOM.render(
  <React.StrictMode>

      <Router>
        <App />
      </Router>
  </React.StrictMode>,
  document.getElementById('root')
)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: